Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    date command gives wrong date


    Hi all,
    I have a script which runs every hour, no issues. But after day light savings this happened in the 12am run:

    script started on march 12th 12:28am & day light savings started on march 11th 2am:

    ++ date +%Y%m%d
    + CURR_DATE=20180312
    + echo 'curr_date is 20180312'

    ++ date -d '1 day ago' +%Y%m%d
    + PREV_DATE=20180310
    + echo 'prev_date is 20180310'

    Just for this particular hour i got the previous date as march 10th instead of march 11th.

    Does the date -d '1 day ago' calculate 24 hours before the current date? because march 11th has 23 hours (day light savings) it took 24 hours and got march 10th 11:28pm date? instead of march 11th 12:28am?

  2. #2
    Trusted Penguin Irithori's Avatar
    Join Date
    May 2009
    Location
    Munich
    Posts
    4,031
    Hi

    I think I can explain it:
    - The script started between 00:00 and 00:59 on March, 12
    - March 11 effectively has 23h in your (assumed) timezone America/New_York, because daylight saving time advances the clock by 1h
    - GNU date seems to handle '1 day ago' as '24h ago'
    Code:
    # TZ='America/New_York' date -d "2018-03-12T00:28:00EDT" +%Y-%m-%dT%H:%M:%S%Z
    2018-03-12T00:28:00EDT
    
    # TZ='America/New_York' date -d "2018-03-12T00:28:00EDT - 1 day" +%Y-%m-%dT%H:%M:%S%Z
    2018-03-10T23:28:00EST
    
    # TZ='America/New_York' date -d "2018-03-12T00:28:00EDT - 24 hours" +%Y-%m-%dT%H:%M:%S%Z
    2018-03-10T23:28:00EST
    
    # TZ='America/New_York' date -d "2018-03-12T00:28:00EDT - 23 hours" +%Y-%m-%dT%H:%M:%S%Z
    2018-03-11T00:28:00EST
    Look at the timezones of the output.
    The date/time together with the timezone is correct in all of the four cases

    But I would have fallen into the same trap.
    One could argue, that 1 day is semantically different from 24 hours on a daylight saving time day.

    My suggestion is to use unix time for date arithmetic in bash.
    As the date/time is an integer then, you can quite easy compare, add/substract without the need of date.
    Plus, the date/time can be converted to <whatever time format> once you need to print it to a console or logfile.

    fwiw, my prefered output timeformat is ISO8601, including the timezone.
    This is both human readable and a machine has a chance to identify the correct date.
    e.g.: 2018-03-12T20:01:31+0100
    You must always face the curtain with a bow.

  3. #3
    Great explanation. Thanks so much!

  4. $spacer_open
    $spacer_close

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •