How to convert string with T to a specific Timezone? - php

So, if I have a string like so: '2017-12-01T16:03:00' and need to convert this string into the timezone of America/New_York, how to convert this string? Not exactly sure what the T is doing in the string and what it's for exactly.
I'm curious on the correct method for this, while I believe the T here is important, I understand the purpose of it. What I've tried here so far:
$string = '2017-12-01T16:03:00';
$time_fix = explode('T', $string);
if (count($time_fix) > 1)
{
$data_date = DateTime::createFromFormat('Y-m-d H:i:s', $time_fix[0] . ' ' . $time_fix[1]);
$output = $data_date->format('Y-m-d H:i:s', new DateTimeZone('America/New_York'));
} else {
$data_date = DateTime::createFromFormat('Y-m-d H:i:s', $time_fix[0] . ' 00:00:00');
$output = $data_date->format('Y-m-d H:i:s', new DateTimeZone('America/New_York'));
}
Not really sure if this is converting the timezone or not, so wondering on what your thoughts are on this? Will the $output variable contain the date and time for the America/New_York timezone? It is very difficult to test this as I don't know what timezone it is currently in when the time string gets created.
Also, wondering if the T here is important and what it means. And how to do this properly for the America/New_York timezone?
UPDATE
Apparently, I found out that the Server Timezone that is creating these Date strings via the API is in Eastern Standard Time already. But if I didn't know this, how would it be converted to UTC? The developers of the API, states that it is UTC in 8601 format, but the timezone is EST. This does not make sense to me. Because, I believe EST is UTC-5, not just UTC. How the heck am I supposed to know this from what seems to be an improperly handled UTC timezone string result from the API? Am I correct in stating that 2017-12-01T16:03:00 is not the correct string for EST timezone from a UTC timezone?

If you do:
$date = new DateTime($info['CreateDate']);
$date->setTimeZone(new DateTimeZone('UTC'));
$date->setTimeZone(new DateTimeZone('America/New_York'));
$output = $date->format('Y-m-d H:i:s');
You are first creating the DateTime object in your default timezone which will affect the timestamp calculation, and then changing the timezone.
Instead, assuming UTC input, you should do:
$date = new DateTime($info['CreateDate'], new DateTimeZone('UTC'));
$date->setTimeZone(new DateTimeZone('America/New_York'));
$output = $date->format('Y-m-d H:i:s');
This way the DateTime object will interpret the input date as UTC time and correctly compute the timestamp. Then setting the timezone is just to get the right date string, it does not affect the underlying timestamp.
I notice that ISO 8601 date strings can specify UTC offsets so in this particular case you may get away without specifying it as no offset is given. This will also make no difference in this case if your default timezone is UTC.
Edit based on new data:
If you know the input is in Eastern Standard Timezone try changing the line where you construct the DateTime object.
$date = new DateTime($info['CreateDate'], new DateTimeZone('EST'));
$date->setTimeZone(new DateTimeZone('America/New_York'));
$output = $date->format('Y-m-d H:i:s');

Explode separate your $string the elements on 2017-12-01 and 16:03:45.
And here you have the answer Timezone conversion in php

Related

Converting a Time from a database to BST with PHP

So I've trying all sorts of combinations to get a date from my database (using Wordpress) to display in British Summer Time and I cannot get anything to work.
Is there any simple solution that can take the date string and make sure that in Summer Time in the UK it's an hour on from UTC time?
$classJson = $class->info;
$classJsonAsArray = json_decode($classJson, TRUE);
$classStartDate = strtotime($class->periodStart);
$classStartTime = date('H:i',$classStartDate);
So currently $class->periodStart returns: 2022-04-06 08:30:00
The time of that event should be 9.30am
All I need it to do is display the correct time, as at the moment, on the front end it displays as 8.30am.
DateTime handles timezones quite well.
$dateStringInUtc = '2022-04-06 08:30:00';
$date = new DateTime($dateStringInUtc, new DateTimeZone('UTC'));
$date->setTimezone(new DateTimeZone('Europe/London'));
echo $date->format('Y-m-d H:i:s'); // will output 2022-04-06 09:30:00
Working with DateTime and timezones like in the accepted answer is the better way.
But it also works with strtotime if the timezone is appended to the date string. Date then returns the local time for a timestamp.
$utcDate = '2022-04-06 08:30:00';
echo date('Y-m-d H:i:s',strtotime($utcDate.' UTC'));

Different behavior when printing DateTime depending on how the timezone was set

Why do I get different dates depending of how I set the timezone on the two code snippets below?
// Setting timezone using setTimezone'
$date1 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-04-04 12:00:00');
$date1->setTimezone(new DateTimeZone('UTC'));
$date1->add(new DateInterval('PT7776000S'));
echo $date1->format('c') . PHP_EOL;
prints 2018-07-03T10:00:00+00:00
// Setting timezone as a param to createFromFormat
$date2 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-04-04 12:00:00', new DateTimeZone('UTC'));
$date2->add(new DateInterval('PT7776000S'));
echo $date2->format('c') . PHP_EOL;
prints 2018-07-03T12:00:00+00:00
When you instantiate DateTime without timezone information, the date is getting interpreted in whatever your default local timezone is; when you then set a new timezone, the date is getting converted to that timezone. I.e.:
$date1 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-04-04 12:00:00');
$date1 is 12:00:00 in, say, Europe/Berlin.
$date1->setTimezone(new DateTimeZone('UTC'));
$date1 is now 10:00:00 in UTC.
When you instantiate DateTime with timezone information, the date is getting interpreted as referring to a time in that timezone, and there's no conversion process afterwards. I.e.:
$date2 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-04-04 12:00:00', new DateTimeZone('UTC'));
$date2 is 12:00:00 in UTC.
It looks like your second example properly adds 90 days (7776000 seconds) t0 the original date.
I think what is happening is that in the first example you are setting the time according to your current timezone (default) and then converting to UTC and then adding the seconds.
In the first example you are setting the timezone to UTC and setting the time, then adding the timeinterval.
Look at this older question's answer:
Timezone conversion in php
Edit: Just saw #deceze already answered similarly. Still, take at the link to see other discussion/examples/etc.

How to get correct timezone value using php

i am changing server time into another time zone using belowcode
$datetime = new DateTime(2014-02-27 03:03:00);
$la_time = new DateTimeZone('America/New_York');
$datetime->setTimezone($la_time);
$dateformat="Y-m-d h:i A";
return $datetime->format($dateformat);
its working fine except AM/PM...
correct result is: 02-26-14 10:03 AM but i am getting result as 02-26-14 10:03 PM.
can you please tell me where the problem
The result will always be based on the original timezone setting. If you want to convert to a different timezone, you must initialize the DateTime object after setting the timezone.
Here's a function to make the job easier:
function convertTimezone($date,$from_tz,$to_tz,$format='Y-m-d h:i A') {
$date = new DateTime($date, new DateTimeZone($from_tz));
$date->setTimezone(new DateTimeZone($to_tz));
return $date->format($format);
}
The function could be improved by checking if the supplied timezones are valid.
Example Usage:
echo convertTimezone('2014-02-27 03:03:00','Pacific/Nauru','Pacific/Chatham');
Output:
2014-02-27 04:48 AM
Demo
Set the timezone when you initialize the DateTime:
$datetime = new DateTime("2014-02-27 03:03:00", new DateTimeZone('America/New_York'));
$dateformat="Y-m-d h:i A";
return $datetime->format($dateformat);
When you set a DateTime, it uses the timezone then in effect. If you change the timezone later, it will change the representation of the time, but the time will be based on the original timezone setting.
EDIT: I didn't read the question carefully enough; you should set the time zone when you initialize the DateTime object, as in the manual.

Changing PHP default timezone not working

I am trying to have a line of code added to an html document that is preceded by the time. I want the time zone to be relative to me, however I cannot change it from the default UTC. I have changed in the php.ini file to PST as well as using date_default_timezone_set('America/Los_Angeles'); and yet it still prints the time 7 hours ahead of my timezone. Heres the code that deals with the time:
session_start();
if(isset($_SESSION['name']))
{
date_default_timezone_set('America/Los_Angeles');
$msg = $_POST['text'];
$fo = fopen("log.html", 'a');
fwrite($fo, "<div class=msgln>(".date("g:i A").") <b style=color:red;>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($msg))."<br></div>
");
fclose($fo);
}
Servers should be set to UTC, and you should not be looking to change the default. Instead, what you want to do is create a DateTime object based on the time, then convert it to the timezone you want, and display.
$now = new DateTime();
$now->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $now->format('g:i A');
I don't know if your format string is valid or not, but the format method is suppossed to be compatible with that accepted by the date() function you were using in your original example.
First make sure you're using a valued timezone. You can find a list of supported timezones in the PHP docs.
The second problem is using date() without specifying the timestamp. This defaults to the timestamp produced by time() which (based on a comment in the documentation) is UTC time. You'll either have to use strftime() or manually subtract the difference from UTC.
If you use 'etc/GMT' you can set the dateTime object to the desired time zone like so:
$dtz = new DateTimeZone('etc/GMT-10');
$dt = new DateTime(date("Y-m-d h:i A"), $dtz);
$date = gmdate("Y-m-d h:i A", $dt->format('U'));

How can I change timezones in a php date?

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";

Categories