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
Related
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()));
?>
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
I'm creating a forum, which also stores the time a post was sent, and I need to convert that into the user's timezone.
Now, the MySQL DataBase stores the time with UTC_TIMESTAMP() (in a column with the DATETIME type), and I created a little function from the code on http://www.ultramegatech.com/blog/2009/04/working-with-time-zones-in-php/ to convert the time to the user's timezone. This is the function:
function convertTZ($timestamp, $tz='UTC', $format='d-m-Y H:i:s') {
// timestamp to convert
$timestamp = strtotime($timestamp);
// the time formatting to use
$format = $format;
// the time zone provided
$tz = $tz;
// create the DateTimeZone object for later
$dtzone = new DateTimeZone($tz);
// first convert the timestamp into an RFC 2822 formatted date
$time = date('r', $timestamp);
// now create the DateTime object for this time
$dtime = new DateTime($time);
// convert this to the user's timezone using the DateTimeZone object
$dtime->setTimeZone($dtzone);
// print the time using your preferred format
$time = $dtime->format($format);
return $time;
}
And I made a test page at http://assets.momo40k.ch/timezones.php.
Now, when I insert a post into the DataBase at, say, 11:50 in my timezone (which is Europe/Rome), it inserts 09:50 in UTC, wich is correct, according to some online timezone converters.
But when I try to convert it back to Europe/Rome with the convertTZ() function, it returns 09:50, as if Europe/Rome is UTC. If I try converting it to a GMT+2:00 timezone, it returns 10:50. Can anyone fugure out why this is?
P.S: I'm not using the CONVERT_TZ() SQL function because my server does not support named timezones, so this function is my workaround.
Make sure your stored timestamps are UTC:
$date = new DateTime($timestamp, new DateTimeZone("UTC"));
$date->format(DATE_W3C); // does it gives the expected result ?
BTW your function can be simplified to this:
function convertTZ($timestamp, $tz='UTC', $format='d-m-Y H:i:s') {
$dtime = new DateTime($timestamp, new DateTimeZone("UTC"))
$dtime->setTimezone(new DateTimeZone("UTC"));
return $dtime->format($format);
}
MySQL always stores TIMESTAMP fields in UTC internally (that's the definition of a unix timestamp, in fact). So when you SELECT or UPDATE/INSERT/REPLACE, the time you get or set is always in the MySQL server's local time zone.
So a common mistake is to store UTC_TIMESTAMP(), which MySQL interprets as a local time and so the current time gets double-converted to UTC when it stores it internally in the field as a unix TIMESTAMP.
I have a date stored in a database in this format:
2011-02-23 13:00:00
I need to return it in ISO8601 format, but it needs to be set to a specific time zone (which is not necessarily the time zone of the server.) What I want to return is this:
2011-02-23T13:00:00-0600
Using this code:
echo date(DATE_ISO8601, strtotime("2011-02-23 13:00:00"));
I get this:
2011-02-23T13:00:00+0000
Is there any way to reset the time zone in the date or strtotime function, or do I need to strip off the 5 rightmost characters and concatenate the desired timezone stamp to the remaining date/time?
EDITED TO ADD:
Although I did accept the solution below of using new DateTime and setting new DateTimeZone, I found an easier way if you don't need to keep resetting the time zone:
date_default_timezone_set('America/Chicago');
$startTime = date(DATE_ISO8601, strtotime("2011-02-23 13:00:00"));
You could use the DateTime class. Datetime objects can be initialized with a specific time zone, and easily transposed to others.
Modified from the manual:
$date = new DateTime('2011-02-23 13:00:00', new DateTimeZone('Pacific/Nauru'));
echo $date->format('c') . "\n";
$date->setTimezone( new DateTimeZone('Europe/Berlin'));
echo $date->format('c') . "\n";
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.