0

I came across something I found a bit confusing when using the date() function.

// Set up unix timestamp 03:34
$t = (3 * 60 * 60) + (34 * 60); // 12840 seconds
echo date('Y-m-d H:i',$t);
// displays Thu, 01 Jan 1970 13:34:00 not
//          Thu, 01 Jan 1970 03:34:00

I was expecting date to return 03:34, but it looks like it might have applied my timezone to it (+1000). My questions are a) does date() apply the current timezone before formatting its output and b) is it possible in PHP to format a date without the application of the timezone? I need the 03:34 to stay that way, but I want to keep the simplicity of using unix-timestamps for my time maths, so would prefer not to use PHPs Date class. Not a huge problem, just something more for interests sake.

Thanks guys Pete

Pete855217
  • 1,570
  • 5
  • 23
  • 35
  • also see these: http://stackoverflow.com/search?q=default+timezone+php – Gordon May 24 '13 at 04:51
  • Sort of answering my own question: I think the solution is to completely avoid the PHP date functions and objects all together, and just do integer maths on my times. Likewise for formatting my times, it's a simple matter to write a basic function that splits the time string into its time parts and output them using echo etc. – Pete855217 May 24 '13 at 05:00
  • you can do that, but that would be reinventing the wheel. And it's prone to errors when you have to handle DST. Really, the DateTime API is fine. If you want your dates in UTC, just set the default to UTC. – Gordon May 24 '13 at 05:11
  • Yep Gordon, I guess that makes sense, just setting UTC at the start of the script so NO timezone conversions occur. Although I must admit I do find the DateTime class somewhat confusing with its reference parameters that sometimes update a parm. – Pete855217 May 24 '13 at 06:41
  • yeah, it should really be immutable. Can use http://www.whitewashing.de/2010/01/08/immutable-datetime-objects.html – Gordon May 24 '13 at 07:01
  • Ah nice to know I'm not alone in finding DateTime a bit confusing! I had a hideous bug yesterday due to this module's design - its unexpected modification of variables was what made it hideous. Thanks for the reference, looks like others have come across the problems with this modules design. I wonder if PHP are looking at redesigning it? – Pete855217 May 24 '13 at 07:13
  • As of PHP5.5 you can use http://php.net/datetimeimmutable – Gordon May 24 '13 at 07:25
  • Thanks Gordon that's great - someone thought of it and fixed it, although it looks like we have to wait until PHP 5.5 is ready for production (not yet). – Pete855217 May 24 '13 at 11:18

0 Answers0