Round-tripping between UNIX seconds-since-epoch and local time loses an hour

Viewed 37

I have anomalous behavior in my bash script and I have found this is the "problem" (it's probably my fault that I don't know the date very well).

If I convert a date in seconds, and try to get a human readable format back, I lost 1 hour

so basically happens this:

~ $ data +%z; date; date -u; data -u +%s
+0200
Sat 24 Sep 2022, 00:02:35, CEST
Fri 23 Sep 2022, 22:02:35, UTC
1663970555

~ $ data -d "1970/01/01 + 1663970555 sec"; date -u -d "1970/01/01 + 1663970555 sec"
Fri 23 Sep 2022, 23:02:35, CEST
Fri 23 Sep 2022, 22:02:35, UTC

What is happening? How can I get the expected result, give "date" 1663970555 seconds and get "Sat 24 Sep 2022, 00:02:35 CEST" back?

I apparently solved with this:

date -ud "1970/01/01 + ${seconds} sec \`date +%:::z\\`"

...but is this the correct way?

Thanks in advance

2 Answers

That's because 1970-01-01 12:00 was at different times in UTC and CET, so adding the same number of seconds leads again to different time moments.

$ date -d '1970-01-01'
Thu 01 Jan 1970 12:00:00 AM CET

$ date -u -d '1970-01-01'
Thu 01 Jan 1970 12:00:00 AM UTC

Use the @ notation instead:

$ date -d @1663970555
Sat 24 Sep 2022 12:02:35 AM CEST  <-----------------------|
$ date -u -d @1663970555                                  |These
Fri 23 Sep 2022 10:02:35 PM UTC      <-------|            |are
$ date -u -d '1970-01-01 + 1663970555 secs'  | These are  |different.
Fri 23 Sep 2022 10:02:35 PM UTC      <-------| the same.  |
$ date -d '1970-01-01 + 1663970555 secs'                  |
Fri 23 Sep 2022 11:02:35 PM CEST  <-----------------------|

Don't use "1970/01/01 + 1663970555 sec" to convert epoch time, because the timezone is used when interpreting 1970/01/01. date allows you to use @ as a prefix for epoch time.

date -d "@1663970555"; date -u -d "@1663970555"
Related