Divyang Shah
Divyang Shah

Reputation: 4007

Get date from a ms since epoch using Bash

I have a json file which needs to be parsed . It has date in long format , sometimes negative long Eg: -201269509000 . If i use this formula t=$(date -d @-201269509000 +'%Y-%m-%d %H:%M:%S'); . This gives an answer like -4408-01-10 00:56:48 .How do i sort this out ? I am trying to do this via shell script.

Upvotes: 0

Views: 93

Answers (2)

jeremysprofile
jeremysprofile

Reputation: 11464

The answer is that date expects numbers in epoch seconds, and your json output is likely in epoch ms (if you know that 4408 BCE is incorrect). Anubhava's comment is wrong, as it assumes your input is positive seconds since epoch.

seconds=-201269509000
t=$(date -d @${seconds%???} +'%Y-%m-%d %H:%M:%S')
echo $t
> 1963-08-16 04:48:11

${var%???} removes the last 3 characters from $var. This is an example of parameter expansion.

Upvotes: 1

Reino
Reino

Reputation: 3443

I have a json file

Then you might as well use a tool like that can parse JSON and can do date-conversions.

Let's say your JSON is {"original_date":-201269509000}.

To get the value of the "original_date" attribute:

xidel -s input.json -e '$json/original_date'
-2.01269509E11

xidel -s input.json -e '$json/integer(original_date)'
-201269509000

Convert (milli)seconds to UTC datetime:

xidel -s input.json -e '$json/integer(original_date div 1000)'
-201269509            # milliseconds to seconds

xidel -s input.json -e '$json/original_date div 1000 * duration("PT1S")'
-P2329DT12H11M49S     # seconds to duration (since 1970-01-01)

xidel -s input.json -e '$json/original_date div 1000 * duration("PT1S") + dateTime("1970-01-01T00:00:00")'
1963-08-16T11:48:11   # UTC datetime

#same as:
date -u -d @-201269509 +%FT%T
1963-08-16T11:48:11

Customize datetime-format:

xidel -s input.json -e '
  $json/original_date div 1000 * duration("PT1S") +
  implicit-timezone() + dateTime("1970-01-01T00:00:00")
'
1963-08-16T13:48:11   # localized datetime taking timezone into consideration

xidel -s input.json -e '
  $json/format-dateTime(
    original_date div 1000 * duration("PT1S") +
    implicit-timezone() + dateTime("1970-01-01T00:00:00"),
    "[Y]-[M01]-[D01] [H01]:[m01]:[s01]"
  )
'
1963-08-16 13:48:11

note: to use implicit-timezone() at least xidel-0.9.9.20200726.7433 is needed.

Upvotes: 0

Related Questions