Answer the question
In order to leave comments, you need to log in
How to get midnight timestamp after time zone change?
Hello.
I'm using Carbon which is a DateTime extension for working with datetime.
There is a task to learn time of midnight for the set timestamp of date for the set time zones.
For example, there is a timestamp = 1485943200 and you need to find out the midnight timestamp for Moscow and Samara on that day.
$initial = Carbon::createFromTimestamp(1485943200);
$moscow_midnight = $initial->copy()->timezone('Europe/Moscow')->modify('midnight')->getTimestamp();
$samara_midnight = $initial->copy()->timezone('Europe/Samara')->modify('midnight')->getTimestamp();
$moscow_midnight = 1485907200
$samara_midnight = 1485907200
which corresponds to midnight simply by 0 GMT, and not by the specified time zones. $moscow_midnight = (new Carbon('midnight', 'Europe/Moscow'))->getTimestamp();
$samara_midnight = (new Carbon('midnight', 'Europe/Samara'))->getTimestamp();
$moscow_midnight = 1485982800
$samara_midnight = 1485979200
Answer the question
In order to leave comments, you need to log in
The point is that it ->modify("midnight")
does not set the time to the beginning of the day. There is no such modifier in the documentation . To set the start of the day you can use ->startOfDay()
.
So your code looks like this:
$initial = Carbon::createFromTimestamp(1485943200);
$moscow_midnight = $initial->copy()->timezone('Europe/Moscow')->startOfDay()->getTimestamp();
$samara_midnight = $initial->copy()->timezone('Europe/Samara')->startOfDay()->getTimestamp();
createFromTimestamp
with createFromTimestampUtc
- so the behavior of the script will be more transparent/obvious. Although, in fact, it will not change, but if, say, someone debugs it, a "strange" situation may turn out. If you run the code in phpio.net/tools/carbonecho '<br />';require 'Carbon/Carbon.php';
use Carbon\Carbon;
$initial = Carbon::createFromTimestamp(0);
echo "{$initial} {$initial->tzName}<br />";
$samara = $initial->copy()->timezone('Europe/Samara')->startOfDay();
echo "{$samara} {$samara->tzName}<br />";
$initial = Carbon::createFromTimestampUtc(0);
echo "{$initial} {$initial->tzName}<br />";
$samara = $initial->copy()->timezone('Europe/Samara')->startOfDay();
echo "{$samara} {$samara->tzName}<br />";
Try like this:
$initial = Carbon::createFromTimestamp(1485943200);
$moscow_midnight = $initial->copy()->setTimezone('Europe/Moscow')->modify('midnight')->getTimestamp();
$samara_midnight = $initial->copy()->setTimezone('Europe/Samara')->modify('midnight')->getTimestamp();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question