I have a little snippet that formats a date for a timestamp like this: (YYYY-MM-DD H:M:S T ) Ex: 2011-09-29 17:00:46 EST or 2011-09-29 17:00:46 EDT
I would like convert EST and EDT to ET and show ET instead, so the users don’t bother about Dayligt savings. How do I do that?
$timeZone = new DateTimeZone('America/New_York');
$processedDate = str_replace(".000000", "", $timestamp);
$dateTime = new DateTime($processedDate, new DateTimeZone('GMT'));
$dateTime->setTimezone($timeZone);
$processedDate = $dateTime->format('Y-m-d H:i:s') . ' ' . $dateTime->format('T');
echo processedDate;
The thing that you want to do is not practical and will lead to your users hating you.
The entire reason behind the named time zones is to accurately represent local time. Representing “Standard” time as a local time when that local area is inside DST is objectively incorrect. Anyone inside that time zone that reads the time is going to be misinformed.
If you need to store and work with dates and times that ignore time zones, then use UTC for that purpose, i.e. storage and normal math. It’s worth remembering that even the good old Unix timestamp is “seconds past midnight, January 1, 1970, UTC”.
If you need to represent times local to the user, then you should allow them to pick their local time zone, and convert it on display. Modern PHP’s DateTime and DateTimeZone make this dead-simple. From the interactive prompt:
No mess, no fuss. It took care of the math for us when we switched the time zone.
In the alternative, if you really, really, really want to flatten out DST timezones, look at getTransitions and getOffset in combination with the various timezone date() formats, I in particular. You can poke and prod at the resulting information to find when the “standard” version of any DST zone next transitions and adjust it accordingly. Remember that different areas transition at different times, and not all areas transition by the same amount … and some don’t transition at all. I think someone mentioned Indiana already.
Normally I’d also provide sample code here, but date math fills me with an insatiable thirst for violence. Whoever decided that 60, 60, 24, 7, 4-6, 12 and 52 were acceptable ways to think about times and dates were evil, evil people. Thankfully they’ve all been dead for between hundreds and thousands of years.