2

I am plucking an ISO8601 variable "$sunrise" from an API. Now I'd like to convert it to the local time. I have the $timeZone (America/Denver style) also as a variable.

An ISO8601 time stamp looks like this: 2019-11-09T11:36:14+00:00

I'd like a people friendly time in local time zone. This will be sunrise.

I have tried every combination in a script I can think of like this:

TZ="$timeZone" newSunrise=echo $date -d "$sunrise" +"%s"

I can't get it to work. Will someone please give me a hand?

1
  • 1
    edit your question to include examples of input and expected output
    – jhnc
    Nov 9, 2019 at 4:26

4 Answers 4

2

You need to put the timezone into the date reference, eg:

var="2019-11-09T11:36:14+00:00"
timeZone="America/Denver"
newsunrise=$(date -d"TZ=\"${timeZone}\" $var")
1

Building on above solution, and generating result in the 'local time'

var="2019-11-09T11:36:14+00:00"
date -d"TZ=$(date +%Z) $var"

Calling date +%Z is required as the environment variable TZ is not always set. In those cases, the system-wide 'local time zone' (I believe /etc/timezone, but there could be additional logic).

1
  • I tried to fashion a line from your suggestion, but it fails too. I'm sure what you've written is fine on the command line and it's my conversion to cron executable code causing the trouble.
    – Geoff Fox
    Nov 9, 2019 at 8:49
1

date on Linux and date on macOS have differences. If you are on macOS, you could install the Linux version of date with brew and then use user4829160's answer with a tiny change.

# Install the Linux version of date
brew install coreutils

# Use gdate instead of date
var="2019-11-09T11:36:14+00:00"
timeZone="America/Denver"
newsunrise=$(gdate -d"TZ=\"${timeZone}\" $var")
echo $newsunrise
0

My code will be going in a program and assigning a variable. I tried adapting both your suggestions, but neither worked as implemented by me.

newSunrise=date -d"TZ=$(date +%Z) $sunrise"

No data is stored in $newSunrise

Also, why did you escape out the quotes? I'm just learning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.