3

I need to convert a date from string in the format "yyyy/mm/dd hh:mm:ss TZ" to UNIX time (TZ = Timezone).

What I have done so far is to convert a date in the format "yyyy/mm/dd hh:mm:ss" without a timezone to timestamp by using

dateYMD="2019/2/28 12:23:11.46"
newt=$(date -d "${dateYMD}" +"%s")
echo ${newt}

and I have the following result.

1551349391

My struggle is to find how both timezone and date/time can be converted to timestamp (unix time) . For example I need 4 variables with the same date/time as dateYMD but in 4 different timezones so that their timestamps would be different.

Here is the latest I have tried

dateYMD="2017/09/09 08:58:09"
timez=$(TZ=Australia/Sydney date -d @$(date +%s -d "${dateYMD}"))
unixTimez=$( date --date "${timez}" +"%s" )
echo ${unixTimez}

that showed me the following error

   date: invalid date ‘чт фев 28 21:23:11 AEDT 2019’

2 Answers 2

10

You don't need to call date twice. Just call it once with TZ set to the timezone you want for that variable.

timesydney=$(TZ=Australia/Sydney date -d "$dateYMD" +%s)
timenyc=$(TZ=US/Eastern date -d "$dateYMD" +%s)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, this is exactly what I needed!
5

Either you do it by setting the TZ= environment variable (see answer of Barmar), or you include the time zone into the time string. This has higher priority than TZ=.

Examples:

TZ=UTC date -d '2019-01-01 12:00 CET' +'%s, %F %T %Z %z'
TZ=CET date -d '2019-01-01 12:00 CET' +'%s, %F %T %Z %z'
TZ=UTC date -d '2019-01-01 12:00 PDT' +'%s, %F %T %Z %z'
TZ=CET date -d '2019-01-01 12:00 PDT' +'%s, %F %T %Z %z'
TZ=UTC date -d '2019-01-01 12:00 +500' +'%s, %F %T %Z %z'

will print

1546340400, 2019-01-01 11:00:00 UTC +0000
1546340400, 2019-01-01 12:00:00 CET +0100
1546369200, 2019-01-01 19:00:00 UTC +0000
1546369200, 2019-01-01 20:00:00 CET +0100
1546326000, 2019-01-01 07:00:00 UTC +0000

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.