Can I get UTC offset from Unix command line?
Asked Answered
H

3

20

I'm writing an autoconf script that needs the current UTC offset. There's no obvious way to get this out of the date program. Is there any straightforward way to get this from a command-line utility, or should I write a test that gets the information and somehow captures it?

Heterotrophic answered 2/5, 2011 at 16:33 Comment(2)
Could you explain why you might need this? It sounds like a very strange requirement.Amazed
because I want to embed compile time in the program, and TIME doesn't return the UTC offset, so I can't turn it into ISO 8601.Heterotrophic
B
34

Try this, and see whether it works for you:

date +%z
Branchiopod answered 2/5, 2011 at 16:38 Comment(0)
W
7

For others doing ISO8601, you might pick some variant of:

date +%Y%m%dT%H%M%S%z     # 20140809T092143-0700
date -u +%Y%m%dT%H%M%S%z  # 20140809T162143+0000
date -u +%Y%m%dT%H%M%SZ   # 20140809T162143Z

I like those because the lack of punctuation supports universal use. Note that the capital Z is 'hard-coded' for UTC - using %Z will put UTC or the other named timezone. If you prefer punctuation:

date +%Y-%m-%dT%H:%M:%S%z      # 2014-08-09T09:21:43-0700
date +%Y-%m-%dT%H:%M:%S%:z     # 2014-08-09T09:21:43-07:00 - NOT ALL SYSTEMS
date -u +%Y-%m-%dT%H:%M:%S%z   # 2014-08-09T16:21:43+0000
date -u +%Y-%m-%dT%H:%M:%S%:z  # 2014-08-09T16:21:43+00:00 - NOT ALL SYSTEMS
date -u +%Y-%m-%dT%H:%M:%SZ    # 2014-08-09T16:21:43Z

Consult man strftime as supported formats vary. For instance, some systems support inserting colons into the offset using %:z, %::z, or %:::z - only two of my five systems do (Debian, Ubuntu do, but Mac, BusyBox, QNX do not).

And I often go back to https://en.wikipedia.org/wiki/ISO_8601 for reference.

Wearproof answered 9/8, 2014 at 16:32 Comment(0)
J
4

Yes, date can do this:

[tomalak@lolphin:~] date -R
Mon, 02 May 2011 17:37:45 +0100

Or, more specifically:

[tomalak@lolphin:~] date -R | awk '{print $6}'
+0100
[tomalak@lolphin:~] date +%z
+0100

Reading date --help is very useful.

Josettejosey answered 2/5, 2011 at 16:37 Comment(2)
That's great. I was looking at the man page and couldn't figure it out.Heterotrophic
I had the same issue with the man page - the trick is man strftimeWearproof

© 2022 - 2024 — McMap. All rights reserved.