AppleDeveloper
AppleDeveloper

Reputation: 1443

On MAC OS machine. How can we convert date in 2017-01-09T09:35:26Z to Timestamp using shell script

I tried some conversion methods but failed. I couldn't interpret the input date format correctly.

Below is the command i used to convert

date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"

And i am looking for a command that works for every Time Zone

Upvotes: 1

Views: 2398

Answers (1)

Montmons
Montmons

Reputation: 1426

Well, what a hassle for such a simple question. (PS: I think it was downvoted for not showing an error message, and the use of the OSX tag might better be replaced for macOS if you are on an up-to-date Mac).

The first problem I found out by reading this post. It explains that in order for your command to work the abbreviations need to be in the system language. This can be solved by adding LANG=C in front of your command.

However, your command still delivered the following error:

Failed conversion of ``Tue Sep 28 19:35:15 EDT 2010'' using format ``%a %b %d %T %Z %Y''
date: illegal time format
usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
            [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

Then, when looking into man date I found this line explaining the -f argument:

-f Use input_fmt as the format string to parse the new_date provided rather than using the default [[[mm]dd]HH]MM[[cc]yy][.ss] format. Parsing is done using strptime(3).

Then, in man strptime I read:

Bugs - The %Z format specifier only accepts time zone abbreviations of the local time zone, or the value "GMT". This limitation is because of ambiguity due to of the over loading of time zone abbreviations. One such example is EST which is both Eastern Standard Time and Eastern Australia Summer Time.

So, I was able to execute your command either like so:

LANG=C date -j -u -f '%a %b %d %T %Z %Y' 'Tue Sep 28 19:35:15 GMT 2010' +%s

Or, like so,

TZ=EDT LANG=C date -j -u -f '%a %b %d %T %Z %Y' 'Tue Sep 28 19:35:15 GMT 2010' +%s

But both aren't actually what you where looking for I guess..

You thus seem to be bitten by a known bug in the default macOS version of strptime.

EDIT

However, if you would have a list with the offset of each timezone (the offset towards GMT), you could do something like:

TZ=EDT LANG=C date -juf '%a %b %d %T %z %Y' 'Tue Sep 28 19:35:15 -0400 2010' +%s

Have a look at this post for more possibilities.

Upvotes: 3

Related Questions