Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different results for date() and gmdate()

Tags:

date

php

time

I found something I can't really explain, maybe someone here can give me a hint.

I have the following test code, that prints 2 formatted timestamps, one for the 31.03.2013 and one for 31.03.2014, using date()and gmdate():

<?php

function print_date($timestamp, $year) {
  // Add timezone offset for germany
  $timestamp += 3600;
  print "in $year\n";
  print "date:   " . date('d.m.Y H:i:s', $timestamp) . "\n";
  print "gmdate: " . gmdate('d.m.Y H:i:s', $timestamp) . "\n";
  print "\n";
}

$end_2013 = 1364684400; // 31.03.2013
$end_2014 = 1396216800; // 31.03.2014
print_date($end_2013, '2013');
print_date($end_2014, '2014');

print "Default timezone: " . date_default_timezone_get() . "\n";

The result surprises me:

in 2013
date:   31.03.2013 01:00:00
gmdate: 31.03.2013 00:00:00

in 2014
date:   31.03.2014 01:00:00
gmdate: 30.03.2014 23:00:00

Default timezone: Europe/Berlin

Where does the difference in 2014 come from? My first thought is daylight savings time, but why doesn't that have an effect in 2013? Why are there 2 hours difference in 2014 but only 1 hour difference in 2013?

like image 335
berliner Avatar asked Mar 06 '14 09:03

berliner


4 Answers

Daylight savings for Berlin starts at

2013 Sunday, 31 March, 02:00 
2014 Sunday, 30 March, 02:00 

Your specified time value for each date is 00:00 on that date, so for 2013 Sunday, 31 March it is before 2am, so no daylight savings; for 2014 it is after 2am on 30th March

like image 102
Mark Baker Avatar answered Nov 05 '22 20:11

Mark Baker


Assuming that you have already checked the docs. gmdate and date

change it

print "date:   " . date('d.m.Y', $timestamp) . "\n";
print "gmdate: " . gmdate('d.m.Y', $timestamp) . "\n";

with this

print "date:   " . date('d.m.Y H:i:s', $timestamp) . "\n";
print "gmdate: " . gmdate('d.m.Y H:i:s', $timestamp) . "\n";

and you will find the difference.

like image 43
zzlalani Avatar answered Nov 05 '22 19:11

zzlalani


Is it a DayLight Saving problem?

According to this , seem 2013-03-31 02:00:00 is changed to 03:00:00

like image 44
user3226688 Avatar answered Nov 05 '22 20:11

user3226688


gmdate() always Format in GMT/UTC date and time But date() always format according to the default time zone

Try this

 <?php
   date_default_timezone_set("Asia/Bangkok");
   echo gmdate('Y-m-d H:i:s');
   echo date('Y-m-d H:i:s');
  ?>
like image 3
beginner Avatar answered Nov 05 '22 20:11

beginner