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.
Related
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
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');
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'));
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";