Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - getting date time using DateTime return different value from date() function

I am trying to get the current timestamp using Carbon or DateTime Class I get wrong date but when I use date() function it return the correct date I run the code on win server 2012 this is my code

dd([
    'Carbon::now()->format("Y-m-d H:i:s P")' => Illuminate\Support\Carbon::now()->format('Y-m-d H:i:s P'), 
    'DateTime()->format("Y-m-d H:i:s P")' => (new DateTime())->format('Y-m-d H:i:s P'), 
    'date("Y-m-d H:i:s P")' => date('Y-m-d H:i:s P'),
    'date("Y-m-d H:i:s P",microtime(true))' => date("Y-m-d H:i:s P", microtime(true)),
    'date("Y-m-d H:i:s P", time())' => date("Y-m-d H:i:s P", time()),
    'Carbon::now()->getTimestamp()' => Illuminate\Support\Carbon::now()->getTimestamp(),
    'microtime()' => microtime(true),
    'time()' => time(),
]);

this is the output that I got

[
  "Carbon::now()->format("Y-m-d H:i:s P")" => "2018-06-25 22:41:59 +03:00"
  "DateTime()->format("Y-m-d H:i:s P")" => "2018-06-25 22:41:59 +03:00"
  "date("Y-m-d H:i:s P")" => "2018-06-19 11:59:22 +03:00"
  "date("Y-m-d H:i:s P",microtime(true))" => "2018-06-25 22:41:59 +03:00"
  "date("Y-m-d H:i:s P", time())" => "2018-06-19 11:59:22 +03:00"
  "Carbon::now()->getTimestamp()" => 1529955719
  "microtime()" => 1529955719.4257
  "time()" => 1529398762
]

the server time is the same as the value of date function

like image 285
Abdulbasset Abu Alnasser Avatar asked Jun 19 '18 09:06

Abdulbasset Abu Alnasser


People also ask

How can I get different time in PHP?

Use date_diff() Function to Get Time Difference in Minutes in PHP. We will use the built-in function date_diff() to get time difference in minutes. For this, we need a start date and an end date. We will calculate their time difference in minutes using the date_diff() function.

What does time () in PHP return?

The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

What does date () do in PHP?

PHP date() Function The PHP date function is used to format a date or time into a human readable format. It can be used to display the date of article was published. record the last updated a data in a database.

Which method will return the current date and time in PHP?

Note that the PHP date() function will return the current date/time of the server!


1 Answers

This is a configurations issue. You have 2 ways to get UNIX-timestamp at PHP: microtime(true) and time(). Carbon and DateTime are using microtime(true) internally.

Here are some details referring to their implementation: https://stackoverflow.com/a/11890155/1921796

like image 128
Leprechaun Avatar answered Oct 13 '22 23:10

Leprechaun