Reputation: 2891
I'm having a bit of trouble with the mktime function. On my production server, if I execute the following:
echo '<p>' . mktime(24, 0,0, 8,29,2009) . ' - 12pm</p>';
echo '<p>' . mktime(23, 0,0, 8,29,2009) . ' - 11pm</p>';
echo '<p>' . mktime(22, 0,0, 8,29,2009) . ' - 10pm</p>';
And then convert those timestamps back to readable format (using www.unixtimestamp.com for quick conversion), the times are all off by one hour. I originally thought this was a problem with 2400 VS 0000, but that wouldn't account for the other dates being off.
Any ideas?
Upvotes: 1
Views: 6385
Reputation: 20279
My problem was that in mktime
I input the day and month with leading zeros. Than the function returned me wrong results. One option would be to remove the leading zero with a function like
$str = ltrim($str, '0');
Source: How to remove all leading zeroes in a string
or
$var = (int)$var;
Source: PHP remove first zeros
I used one possibility from soulmerge:
$date = new DateTime($year . '-' . $month . '-' . $day . ' ' . $hour . ':' . $minute . ':' . $seconds);
$match_time = $date->getTimestamp();
But the timezone should be always set (either with date_default_timezone_set()
or directly with DateTime
.
Upvotes: 0
Reputation: 75714
Your server has a different time zone than you are expecting. Unix timestamps are measured in seconds since 1.1.1970 00:00:00 GMT, so you have a hidden time zone conversion in your code. You can either
gmmktime()
to create a timestamp for a GMT date,date_default_timezone_set()
.Upvotes: 5
Reputation: 24462
I just ran the following from the command line and got the following (expected) output. What happens if you run them?
$ php -r "echo date('H:i:s Y-m-d', mktime(24, 0, 0, 8, 29, 2009));"
00:00:00 2009-08-30
$ php -r "echo date('H:i:s Y-m-d', mktime(23, 0, 0, 8, 29, 2009));"
23:00:00 2009-08-29
$ php -r "echo date('H:i:s Y-m-d', mktime(22, 0, 0, 8, 29, 2009));"
22:00:00 2009-08-29
Upvotes: 0