5

I had this working on Ubuntu but I'm now trying to run the script on OSX but it seems that the formatting of date is different.

Originally I had:

date -d "$MODDATE" +%F" "%H":"%M

where $MODDATE is a unix timestamp generated with stat

However the above date function doesn't work the same way on BSD versions. How can I convert the timestamp to the date in the following format: YYYY-MM-DD HH:MM ?

1
  • In what format is $MODDATE? There are plenty of different stat commands that can produce a variety of formats. If you can get it in number of seconds from the epoch, do that. Commented Aug 12, 2013 at 23:47

2 Answers 2

7

You can use the command:

$ date -jf "<input format>" "<input value>" +"<output format>"

For example:

$ date -jf "%Y-%m-%d %H:%M" "2011-11-13 08:11:02" +"%Y-%m-%d %H:%M"
2013-08-13 09:11

References

2

To generate a timestamp: date +%s.

And how to convert that timestamp?

macOS

Use the following:

date -jf "%s" "<timestamp value>" +"%Y-%m-%d %H:%M"

And with 1638449406 as timestamp:

date -jf "%s" "1638449406" +"%Y-%m-%d %H:%M"

it will print:

2021-12-02 13:50

Unix:

Use the following:

date -ud @<timestamp value> +"%Y-%m-%d %H:%M"

Again, with 1638449406 as timestamp:

date -ud @1638449406 +"%Y-%m-%d %H:%M"

it will print:

2021-12-02 13:50
1
  • date -ud @1638449406 +"%Y-%m-%d %H:%M" is the GNU syntax, not Unix syntax and would give you the UTC time, not local time for that Unix epoch time. Commented Nov 12, 2021 at 16:20

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.