1

I can format dates and time pretty flexibly with strftime, but from what I can see, this only will give times in my local timezone; I can add the timezone offset (e.g. '%Y %m %d-%H:%M:%S%z' for a particular time yields 2022 02 14 16:21:35-0800), but what I actually want is the datetime for UTC. (For that example, 2022 02 15 00:21:35.) Is this possible with strftime?

(Context: I'm fiddling with git log --date=format trying to get a format which matches go.mod fake versions. The --date=format:'%foo%bar' option, for defining custom formats, delegates to system strftime. I'm on Mac OSX Monterey and using bash. EDIT: Solution was somewhat more complex due to being used in git; changed the question description to reflect that.)

1
  • Note for anyone trying to duplicate the go.mod pseudo-version format; you want --format=v0.0.0-%cd-%h\ %s --abbrev=12, rather than using %ad. . . . . . My full alias, including the answer, is TZ=UTC0 git log --date=format-local:'%Y%m%d%H%M%S' --format=v0.0.0-%cd-%h\ %s --abbrev=12.
    – jkmartin
    Commented Mar 22, 2022 at 20:45

1 Answer 1

2

The strftime() C function only formats a date/time. You would pass it the result of gmtime() to get UTC time or localtime() to get the local time.

date displays the local time by default, but can be told to display UTC time with the -u option.

localtime() computes the local time from a given epoch time (like the value returned by time()) based on the contents of the $TZ environment variable which specifies the timezone. And if that variable is not defined, the behaviour varies between systems.

If you have tools that always display local time and cannot be told to switch to universal time, you can always call them in an environment where $TZ specifies a timezone with constant zero offset to UTC.

TZ=UTC0 date

Has the same effect as:

date -u

TZ=UTC0 defines a locale called UTC that is of 0 offset to UTC, so you get UTC time and date +%Z gives you "UTC", so with that value of $TZ, localtime() behaves just like gmtime().

For git's --date=format, you also need to append -local, for the date to be expressed as local time instead of the timezone stored in the commit. So:

TZ=UTC0 git log --date=format-local:'%Y %m %d-%T'
3
  • Nope, that doesn't do anything here. git log -1 --date=format:'%Y %m %d %H%z' 1e15a58a hands me back 2022 01 24 17-0800. TZ=UTC0 git log -1 --date=format:'%Y %m %d %H%z' 1e15a58a hands me back the exact same string.
    – jkmartin
    Commented Mar 3, 2022 at 20:45
  • @jkmartin, see edit. Commented Mar 3, 2022 at 21:03
  • Ahah. Yes, that works. Thanks.
    – jkmartin
    Commented Mar 7, 2022 at 19:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .