简体   繁体   中英

March 14th not 86400 seconds long?

In my web application, I have users input a date in a simple textbox. That input (after being sanitized, of course), is run through strtotime(), and 86399 is added to it, to make that timestamp the end of the day written (11:59:59). This is for due date purposes (so if the date passes, the application raises a flag)

For the days I tested, it worked...

January 5th saved as january 5th, at the end of the day.

March 13th saved as March 13th

March 15th saved as March 15th

March 14th, for whatever reason, saved itself as March 15th.

Is March 14th mysteriously a couple seconds short or something??


Update: Thanks to oezi for the solution - worked like a charm. Code as requested:

Old code:

if ($_POST['dateto'] != '') {
    $dateto = strtotime(mysql_real_escape_string($_POST['dateto'])) + 86399;
}

New code:

# Offset to "end of day"
list($y,$m,$d) = explode('-',date("Y-m-d",strtotime($_POST['dateto'])));
$d++;
$dateto = strtotime($y . '-' . $m . '-' . $d) - 1;

March 14, 2010 is the day Daylight Saving Time begins in the United States. So if you're doing math in the local time zone, March 14 is only 23 hours long.

我会假设,因为这是夏令时的开始

Like others said, this is because of daylight saving time. To solve this problem, you could do this:

<?php
list($y,$m,$d) = explode('-',date("Y-m-d",strtotime($date_from_user)));
$h = 23;
$i = 59;
$s = 59;
$mytimestamp = "$y-$m-$d $h:$i:$s";
?>

In all time zones that "support" daylight savings time , you'll get two days a year that don't have 24h. They'll have 25h or 23h respectively. And don't even think of hardcoding those dates. They change every year, and between time zones.

Oh, and here's a list of 34 other reasons that you hadn't thought about, and why you shouldn't do what you're doing .

What database are you using? there has to be a better way to do this (most date manipulation commands are database specific). In SQL Server, I'd just add 1 day to the date and then subtract 1 second:

DECLARE @YourDate datetime
SET @YourDate='2010-03-14'

SELECT DATEADD(ss,-1,@YourDate+1)

OUTPUT:

-----------------------
2010-03-14 23:59:59.000

(1 row(s) affected)

for what it is worth, I'd much prefer to have a condition: < NextDay than <=CurrentDay12_59_59

http://tycho.usno.navy.mil/leapsec.html

Not all days are 86400 seconds long.

This is a rare event. And (historically) never scheduled in March.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM