mari
mari

Reputation: 874

How to subtract a day from an invalid date in shell script?

I'm working on a script to automate the download of information from a customer in the period from 00:00 to 23:59 on the same day. To make the correct treatment of the first day of daylight saving time (10/15/2017, in my timezone - BRST), I need to check the timezone of the previous day. However, when I will subtract one day from the first valid time,

date --date="20171015 01:00 -1 day" +%Y-%m-%d

the result is the next day 2017-10-16, not the previous day 2017-10-14. Could anyone help me understand what I might be doing wrong and how should I do this operation in the right way?

Upvotes: 2

Views: 361

Answers (2)

glenn jackman
glenn jackman

Reputation: 246807

It appears the "BRST" timezone is not very useful: stick to Olson timezone names

$ TZ=BRST date --date="20171015 00:30" "+%F %T"
2017-10-15 00:30:00

$ TZ=America/Sao_Paulo date --date="20171015 00:30" "+%F %T"
date: invalid date ‘20171015 00:30’

Upvotes: 0

chepner
chepner

Reputation: 531165

I don't really trust GNU date's arithmetic. Instead, I would convert your starting time to seconds since the UNIX epoch, subtract 86400 seconds, and convert the result back to a day. Those conversion routines take daylight saving time into account.

$ TZ=BRST date +%s --date "20171015 01:00"
1508029200
$ TZ=BRST date +%F-%T --date @$((1508029200 - 86400))
2017-10-14-01:00:00

Upvotes: 2

Related Questions