Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get midnight of current day in a specified timezone in PHP?

Tags:

php

datetime

I have a server in New York, and a "client" in California which expects that server to figure out midnight of the current day in California, which is not the same as New York's for three hours out of the day.

I have only been able to calculate midnight for the current day as is seen by New York, but I need to be able to calculate midnight of the current day for California (or any other arbitrary timezone)

I do have access to the timezone's offset from UTC.

$tzOffset = "-700"; // Timezone offset from UTC (in this case, PDT)

The (semi-working) method that I'm using right now is

strtotime("00:00:00 " . $tzOffset);

On Jun 25 at 10:00 PM PDT, this method is returning Jun 26 at 12:00 AM PDT as midnight, when it should be returning Jun 25 12:00 AM PDT.

like image 932
kfreezen Avatar asked Jun 26 '14 06:06

kfreezen


People also ask

What is midnight timestamp?

5. 00:00 is midnight at the beginning of a day, 24:00 is midnight at the end of a day.

How can I change current date in PHP?

Change YYYY-MM-DD to DD-MM-YYYY In the below example, we have date 2019-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2019 in DD-MM-YYYY format. $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate)); echo "New date format is: ".


1 Answers

// create time from string
$date_time = new Datetime('midnight', new Datetimezone('America/Los_Angeles'));
// string representation of time in America/Los_Angeles
echo $date_time->format('Y-m-d H:i:s') . PHP_EOL;
$date_time->setTimezone(new Datetimezone('America/New_York'));
// string representation of the same time in America/New_York
echo $date_time->format('Y-m-d H:i:s') . PHP_EOL;

http://php.net/manual/en/datetime.formats.php

like image 59
sectus Avatar answered Oct 29 '22 17:10

sectus