Git:显示UTC时间日期

29
以下命令以JSON格式显示最后一次Git提交的一些元数据:
以下命令以JSON格式显示最后一次Git提交的一些元数据:

git show --quiet HEAD --pretty=format:"{\"hash\":\"%h\", \"author\":\"%cn\", \"commit date\":\"%cd\"}"

{
  "hash":"0fc0fc0", 
  "author":"Adam Matan",
  "commit date":"Sun Jan 26 12:26:19 2014 +0200"}
}

有没有一种方法可以以UTC / GMT时区表示日期,例如"Sun Jan 26 10:26:19 2014"


1
UTC是一个时区,而不是一个格式。在这种情况下,你所说的UTC格式是什么意思? - CB Bailey
@CharlesBailey 确实,已修复。 - Adam Matan
3个回答

46

你可以使用这个:

TZ=UTC0 git show --quiet --date=local --format="%cd"

如果您想控制日期格式,可以这样做:

TZ=UTC0 git show --quiet --date='format-local:%Y%m%dT%H%M%SZ' --format="%cd"

更新于2021-10-16:感谢@alex-shpilkin的提醒,更改TZ=UTCTZ=UTC0

TZ=UTC已被弃用,正确的写法应该是TZ=UTC0。


看起来可以工作 :-) 更易读一些:TZ=UTC git show --quiet --date='format-local:%Y-%m-%d %H:%M:%SZ' --format="%cd" - KajMagnus
5
如果您满意于Git的ISO格式(较短的格式字符串),也可以使用TZ=UTC git show --quiet --date=iso-local - Dato
很遗憾,此命令不可移植:您不能在Windows上直接运行它,并且在其他不识别“TZ”环境变量的系统上也无法正常工作。 - dolmen
2
@dolmen 将 TZ 设置为 UTC 甚至不符合 POSIX 标准;Windows 确实识别 TZ 变量,但应将其设置为 POSIX 规定的值 UTC0。(我假设您指的是这个问题,而不是 Windows 中的 cmd.exe 不支持本地变量赋值,因为在 shcmd.exe 之间的可移植性基本上是不可能的。) - Alex Shpilkin

4

我在日志数据格式中并没有看到UTC格式(见此答案)。

从您提供的格式中,最接近的是:

git config log.date local

C:\Users\VonC\prog\git\git\>git show --quiet HEAD --pretty=format:"{\"hash\":\"%h\", \"author\":\"%cn\", \"commit date\":\"%cd\"}"
{"hash":"b594c97", "author":"Junio C Hamano", "commit date":"Thu Jan 23 10:00:28 2014 -0800"}

C:\Users\VonC\prog\git\git\>git config log.date local

C:\Users\VonC\prog\git\git\Documentation\technical>git show --quiet HEAD --pretty=format:"{\"hash\":\"%h\", \"author\":\"%cn\", \"commit date\":\"%cd\"}"
{"hash":"b594c97", "author":"Junio C Hamano", "commit date":"Thu Jan 23 19:00:28 2014"}

所以从ISO的角度来看:

"Thu Jan 23 10:00:28 2014 -0800"

本地化:

"Thu Jan 23 19:00:28 2014"

正如评论所述,这不是UTC时间,除非您的机器本地时间已经是UTC。


邮件列表上讨论过:

添加user.hideTimezone以设置UTC时区

默认情况下,创建并共享提交会暴露用户的时区。

"commit --date=YYYY-MM-DDThh:mm:ss+0000"足以将作者时间设置为UTC,但提交时间并非UTC。
但用户根本不应该传递任何标志。

Git应完全停止访问、记录和共享用户的时区,就此打住。

如果无法做到这一点,Git默认情况下应停止访问、记录和共享用户的时区,但如果个别用户希望在其提交中包含时区信息,则可以选择加入。

Git维护者Junio C. Hamano回答道:

You are free to run

$ TZ=GMT git commit

if you wanted to opt out of the feature, but this has been the default since day one and people expect Git to behave this way.

此外:

For now, using the --date argument on git commit allows you to also pass a timezone:

git commit --date="$(TZ=PST date)"

这个补丁(用于添加user.hideTimezone)尚未完全开发。


1
这不是UTC,除非您的系统配置了时区设置为UTC。怎么可能成为被接受的答案? - dolmen

4

作为补充,'unix'将打印原始时间戳,如1700125979。使用TZ=UTC date --date='@1700125979'将其转换为2023年11月16日星期四上午09:12:59 UTC - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接