get timezone offset from UNIX timestamp in PHP - php

In PHP 7.2, if I do this:
<?php
$dt = new DateTime('#1522680410', new DateTimeZone(date_default_timezone_get()));
$tz_offset = $exp->getOffset();
?>
$tz_offset always returns 0. However, if I set a date and not a UNIX timestamp (i.e., '2018-01-02' instead of '#1522680410') it shows the correct offset value.
Is there a way to have the timestamp return the timezone offset in one step like above?

Unix timestamp is always in UTC timezone (or ±00:00 offset). If not, you are doing something nasty :)
If you take a look at DateTime::__construct(), you will see note on 2nd argument:
The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. #946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
Change timezone after you have created DateTime object:
$dt = new DateTime('#1522680410');
$dt->setTimezone(new DateTimeZone(date_default_timezone_get()));

Apparently you can do it this way:
<?php
$dt = new DateTime(DateTime::createFromFormat('U', '1522680410')->format('Y-m-d'), new DateTimeZone(date_default_timezone_get()));
?>

Related

Create php DateTime object from unix timestamp, set timezone in one line

I know that in php you can create an DateTime object from a unix timestamp and set its timezone in multiple lines like the following:
$date = new DateTime('#' . $timestamp);
$date_with_timezone = $date->setTimezone(new DateTimeZone('America/Chicago'));
I would like to do this on one line however. The following does not work:
$date_with_timezone = new DateTime('#' . $timestamp, new DateTimeZone('America/Chicago'));
Is there any way to create a php DateTime object from a unix timestamp, and set a timezone on the same line?
Class member access on instantiation (e.g. (new foo)->bar()) support was introduced in PHP version 5.4 (see the release notes), so you can do this:-
$date = (new DateTime('#' . $timestamp))->setTimezone(new DateTimeZone('America/Chicago'));
See it working
There is a note on the timezone documentation:
Note:
The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. #946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
http://php.net/manual/en/datetime.construct.php
As a workaround, you could probably create a function and pass in the timestamp and time zone. Then you could accomplish the goal of keeping the variable assignment on the same line. In the function, you could create the DateTime object using the timestamp, then assign the timezone and return it.
I correct my response,
it is really possible in one line ...
$time_stamp = 1671231344;
$Date_Object = ( new DateTime('now',new DateTimeZone('Europe/Paris')) )
->setTimestamp($time_stamp)
->format('d/m/Y H:i');
// test :
echo $Date_Object;
Test :
16/12/2022 23:55

DateTime->format(epoch) returning the wrong date

I am working on a project and I am having an issue formatting an epoch time to a human readable time.
I have the following epoch time 1428512160 and when I put this through epochconverter.com I get the human time of 08/04/2015 17:56:00 GMT+1:00 DST as expected.
I then use the following code in order to perform the conversion from the epoch time to a human date time.
$dt = new DateTime($supportDetails["Reported"]);
$reportedTimeString = $dt->format('d-m-Y H:i:s');
$supportDetails[Reported] is the epoch time (I've printed it so I know it's correct).
The result I get back however is 08-04-2160 14:28:51.
You need to add an # for the timestamp in the DateTime class, like this:
$dt = new DateTime("#" . $supportDetails["Reported"]);
//^ See here
You can also see this in the manual. And a quote from there:
Unix Timestamp "#" "-"? [0-9]+ "#1215282385"
Also note that the current timezone is getting ignored, which you can also see in the manual:
Note:
The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. #946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
Printing date and time is correct.
Its based on what GMT you have set in your PHP.
If you printing with GMT you will get required result.
Try the following code:
$reportedTimeString = date("d-m-Y H:i:s", $supportDetails["Reported"]);
Or the following:
$date = new DateTime();
$date->setTimestamp($supportDetails["Reported"]);
$reportedTimeString = $date->format("d-m-Y H:i:s");
The problem I see is with your formatting.
If you look at PHP's date function you can see that you just need to write each portion of the desired date & time into a string.
The following formatting gives the same output you were looking for:
$dt = new DateTime($supportDetails["Reported"]);
$reportedTimeString = $dt->format('d/m/Y H:i:s \G\M\TP T');

How can I create a DateTime object from a string that is already in a specific timezone?

I am working within an environment (wordpress) in which all default timezone settings are set to UTC.
Within that, I want to create a timer function that deals with the time always in the local server time (+8).
The goal is to have a function that returns a DateTime object to any given date (input with a 'Y-m-d H:i:s' format, always in the local +8 timezone
function datetime_obj($date = NULL) {
$date_new = new DateTime($date);
$date_new->setTimezone(new DateTimeZone('Asia/Hong_Kong'));
return $date_new;
}
This works great when I try to get today's date/time information ($date = NULL). However if I have an existing time (in HKG time) as a string (say from a datetime field in a MySQL database), I cannot generate a new datetime object from it since it is treated as UTC. The resulting DateTime object from the function above has always added 8 hours to it.
How can I change the above function so that a $date that is inserted is accepted as already being in the correct +8 timezone and not changed +8 as an output?
I haven't tried it, but the doc says:
public DateTime::__construct() ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
time: A date/time string. Valid formats are explained in Date and Time
Formats. Enter NULL here to obtain the current time when using the
$timezone parameter.
timezone: A DateTimeZone object representing the timezone of $time. If
$timezone is omitted, the current timezone will be used.
Note: The $timezone parameter and the current timezone are ignored
when the $time parameter either is a UNIX timestamp (e.g. #946684800)
or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
http://at2.php.net/manual/en/datetime.construct.php
so... this:
$date_new = new DateTime($date."+08:00");
or this:
$date = new DateTime($date, new DateTimeZone('Asia/Hong_Kong'));
should do the job

convert to UTC without changing php timezone settings

How can I convert the time zone of a date string in php without changing the default time zone. I want to convert it locally to display only. The php time zone settting should not be modified.
EDIT:
My source time is a UTC string, I want to convert it to a different format, retaining the time zone as UTC, but php is converting it to local timezone.
The code I used was:
date('Y-m-d H:i::s',strtotime($time_str));
How do I retain timezone?
$src_tz = new DateTimeZone('America/Chicago');
$dest_tz = new DateTimeZone('America/New_York');
$dt = new DateTime("2000-01-01 12:00:00", $src_tz);
$dt->setTimeZone($dest_tz);
echo $dt->format('Y-m-d H:i:s');
Note that if the source time is UTC, you can change the one line to this:
$dt = new DateTime("2000-01-01 12:00:00 UTC");
Edit: Looks like you want to go to UTC. In that case, just use "UTC" as the parameter to the $dest_tz constructor, and use the original block of code. (And of course, you can omit the $src_tz parameter if it is the same as the default time zone.)

How do you get around PHP's DateTime usage of UTC for timestamps?

The PHP manual for DateTime states
The $timezone parameter and the
current timezone are ignored when the
$time parameter either is a UNIX
timestamp (e.g. #946684800) or
specifies a timezone (e.g.
2010-01-28T15:00:00+02:00).
Which means that when I do
$time1 = new DateTime('#'.time());
$time2 = new DateTime();
I will have two different results since my default timezone is not UTC. How do you handle this? I don't want to change my server timezone - yet I need timestamps to be output in my timezone.
Use:
$time1 = new DateTime(NULL, "<your timezone here>");
Or you can specify your preferred format in the first field and leave the timezone NULL.

Categories