Bash convert epoch to date, showing wrong time

BashDateEpoch

Bash Problem Overview


How come date is converting to wrong time?

result=$(ls /path/to/file/File.*)
#/path/to/file/File.1361234760790

currentIndexTime=${result##*.}
echo "$currentIndexTime"
#1361234760790

date -d@"$currentIndexTime"
#Tue 24 Oct 45105 10:53:10 PM GMT

Bash Solutions


Solution 1 - Bash

This particular timestamp is in milliseconds since the epoch, not the standard seconds since the epoch. Divide by 1000:

$ date -d @1361234760.790
Mon Feb 18 17:46:00 MST 2013

Solution 2 - Bash

For Mac OS X, it's date -r <timestamp_in_seconds_with_no_fractions>

$ date -r 1553024528
Tue Mar 19 12:42:08 PDT 2019

or

$ date -r `expr 1553024527882 / 1000`
Tue Mar 19 12:42:07 PDT 2019

or

$ date -r $((1553024527882/1000))
Tue Mar 19 12:42:07 PDT 2019

Solution 3 - Bash

You can use bash arithmetic expansion to perform the division:

date -d @$((value/1000))

Note that "value" is a bash variable with the $ being optional; i.e., $value or value can be used.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbobbyrne01View Question on Stackoverflow
Solution 1 - BashandrewdotnView Answer on Stackoverflow
Solution 2 - BashMarcusView Answer on Stackoverflow
Solution 3 - BashRichard JessopView Answer on Stackoverflow