1

I have exist microsecond timestamp = 1484923604957 and I want create DateTime object or just date, for then set in db in table with column created_at - datetime. I don't want change type field in DB. Now I convert to date like this

        $seconds = $mil / 1000;
    return date("Y-m-d H:i:s", $seconds);

and in DB have 2017-01-20 14:46:44

and then when get have date without microseconds

created_at = "2016-12-29 14:42:05"

I create DateTime

        $dateTimeClass = date_create_from_format('Y-m-d H:i:s', $date);
    return $dateTimeClass;

and in response

   $dateTimeClass->getTimestamp()*1000

this is last microsecond

How to correct convert to DatTime (or date) with microseconds and back to microseconds?

shuba.ivan
  • 3,824
  • 8
  • 49
  • 121

2 Answers2

0

You need to change db field type for created_at - DATETIME to DATETIME(6) for microseconds. Without that you won't get exact time in microseconds as it doesn't get stored in database.

Parth Shah
  • 346
  • 1
  • 6
  • I have type ` `created_at` datetime NOT NULL,` what type is it DATETIME(6) and how to change ? – shuba.ivan Feb 20 '17 at 11:02
  • @shuba.ivan refer this http://stackoverflow.com/questions/26299149/timestamp-with-a-millisecond-precision-how-to-save-them-in-mysql – Parth Shah Feb 20 '17 at 12:05
0

You can use $dateTime->format('u') to convert your object to microseconds if it was created with microseconds. Please refer to the documentation for date.

Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

3472948
  • 801
  • 4
  • 15