Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get local time in php?

Tags:

php

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?

like image 776
Alexander Avatar asked Jul 23 '14 15:07

Alexander


People also ask

How to get time using PHP?

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 TimeStamp format in PHP?

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).

What is PHP time function?

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()


2 Answers

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.

like image 133
N.B. Avatar answered Oct 24 '22 11:10

N.B.


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.

like image 43
Shiplu Avatar answered Oct 24 '22 13:10

Shiplu