I am trying to get the local time using php. I wrote two different versions, but they both give the wrong time
date_default_timezone_set('UTC');
$now = new DateTime();
echo $now->getTimestamp();
Another way
date_default_timezone_set('America/New York');
echo strtotime("now")."<br/>";;
$now = new DateTime();
echo $now->getTimestamp();
In both cases I get the time 4 fours ahead of my local time. There is any other way to get the local time?
The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
What is a TimeStamp? A timestamp in PHP is a numeric value in seconds between the current time and value as at 1st January, 1970 00:00:00 Greenwich Mean Time (GMT).
The time() function is a built-in function in PHP which returns the current time measured in the number of seconds since the Unix Epoch. The number of seconds can be converted to the current date using date() function in PHP. Syntax: int time()
DateTime::getTimestamp()
returns unix timestamp. That number is always UTC. What you want is format the date according to your time zone.
$dt = new DateTime("now", new DateTimeZone('America/New_York'));
echo $dt->format('m/d/Y, H:i:s');
Or use a different date format, according to what you need.
Also, you can use DateTime library for all your date needs. No need to change server's default timezone every time you want to fetch the date.
Simply use function date_default_timezone_set(). Here is example:
<?php
date_default_timezone_set("Asia/Dhaka");
echo date('d-m-Y h:i:s A');
?>
Hope it will help, Thanks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With