如何在Git Bash中利用现有工具将UTC时间戳转为相对日期格式?
用Git Bash自带工具实现UTC时间戳转相对日期
方案一:纯Bash+Awk实现(推荐)
这个方案只依赖Git Bash预装的bash、awk和date工具,跨平台且无hack操作,完全符合你的要求。
实现脚本
把下面的代码存为relative-date.sh,或者直接嵌入到你的脚本里:
#!/bin/bash # 检查输入参数是否正确 if [ $# -ne 1 ]; then echo "用法: $0 <UTC时间戳>" exit 1 fi timestamp=$1 current=$(date +%s) diff=$((current - timestamp)) # 通过Awk计算时间差并生成相对描述 awk -v diff="$diff" ' BEGIN { if (diff < 60) { print "just now" } else if (diff < 3600) { mins = int(diff / 60) print mins " minute" (mins > 1 ? "s" : "") " ago" } else if (diff < 86400) { hours = int(diff / 3600) print hours " hour" (hours > 1 ? "s" : "") " ago" } else if (diff < 2592000) { # 30天以内 days = int(diff / 86400) print days " day" (days > 1 ? "s" : "") " ago" } else { # 超过30天显示具体日期,可根据需求调整格式 cmd = "date -d @" diff " +\"%Y-%m-%d\"" cmd | getline date_str close(cmd) print date_str } } '
使用方法
# 给脚本添加执行权限(仅第一次需要) chmod +x relative-date.sh # 转换指定时间戳 ./relative-date.sh 1746111769
方案二:复用Git内置格式化逻辑(轻量hack)
如果确实想复用Git的%cr相对日期逻辑,可以用这个更干净的hack,不用手动维护虚拟仓库:
#!/bin/bash if [ $# -ne 1 ]; then echo "用法: $0 <UTC时间戳>" exit 1 fi timestamp=$1 # 创建临时目录并初始化仓库,提交后获取相对日期 temp_dir=$(mktemp -d) cd "$temp_dir" || exit 1 git init > /dev/null GIT_COMMITTER_DATE="@$timestamp" git commit --allow-empty -m "temp" --date="@$timestamp" > /dev/null git log -1 --format='%cr' # 清理临时文件 cd - > /dev/null rm -rf "$temp_dir"
这个方案会自动清理临时文件,比手动建仓库省心,但本质还是借助Git的提交时间格式化功能。
方案三:Git对象级别的进阶hack
直接构造伪Git提交对象,无需创建实际仓库,全程在内存处理:
#!/bin/bash if [ $# -ne 1 ]; then echo "用法: $0 <UTC时间戳>" exit 1 fi timestamp=$1 # 构造伪提交对象的内容,用git show格式化相对日期 echo "commit $(git hash-object -t commit -w --stdin <<EOF tree $(git hash-object -t tree /dev/null) author Temp <temp@example.com> $timestamp +0000 committer Temp <temp@example.com> $timestamp +0000 temp commit EOF )" | git show --no-patch --format='%cr'
这个方案效率更高,但需要对Git的对象结构有基础了解。
内容的提问来源于stack exchange,提问作者LyrePyre
相关产品推荐
相关产品推荐

