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?

vy32
  • 28,461
  • 37
  • 122
  • 246
  • Could you explain why you might need this? It sounds like a very strange requirement. – Peter Eisentraut May 02 '11 at 17:12
  • 1
    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. – vy32 May 03 '11 at 03:22

3 Answers3

32

Try this, and see whether it works for you:

date +%z
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Till
  • 3,084
  • 17
  • 18
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.

sage
  • 4,863
  • 2
  • 44
  • 47
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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055