如何显示给定日期是多久以前。例如:
echo "File was modified `date -r file.txt`"
这将呼应:
File was modified Tue Jan 7 00:52:40 GMT 2014
但是我希望它类似于以下内容:
File was modified 3 seconds ago
File was modified 1 hour ago
File was modified 2 days ago
File was modified 3 weeks ago
或类似的东西。关键是当包含在句子中时,它应该很容易理解。
(这不是这个问题的重复,只指定了整天。
我今天遇到了类似的问题,最终为此编写了一个函数:
time_ago() {
if (( $# < 1 )); then
local u=$(tput smul) # underline
local n=$(tput rmul) # no underline
echo "usage: time_ago ${u}timestamp_ago${n} [${u}timestamp_now${n}]"
exit 1
fi
local minutes=60
local hours=$(( 60 * minutes ))
local days=$(( 24 * hours ))
local diff=$(( ${2:-$(date +%s)} - $1 ))
local human
if (( diff < 30 )); then
human="${diff} seconds"
elif (( diff < 90 )); then
human="1 minute"
elif (( diff < 1 * hours )); then
human="$(( (diff + minutes / 2) / minutes )) minutes"
elif (( diff < 1 * hours + 30 * minutes )); then
human="about 1 hour"
elif (( diff < 1 * days )); then
human="about $(( (diff + hours / 2) / hours )) hours"
elif (( diff < 2 * days)); then
human="1 day"
else
human="$(( (diff + days / 2) / days)) days"
fi
echo "$human ago"
}
if [[ "$0" = "./time_ago" ]];then
time_ago 1556324045 1556540404 # 3 days ago
time_ago 1556424045 1556540404 # 1 day ago
time_ago 1556534045 1556540404 # about 2 hours ago
time_ago 1556536045 1556540404 # about 1 hour ago
time_ago 1556539145 1556539875 # 12 minutes ago
time_ago 1556539900 1556539921 # 21 seconds ago
time_ago
fi
如果您想评论/编辑,它可以作为要点使用。间隔的灵感来自轨道的distance_of_time_in_word。
您可以使用一些模块化算术来完成此操作。例如:
DATE=$(date -r file.txt +%s)
NOW=$(date +%s)
DIFF=$(expr $NOW - $DATE)
SEC=$((DIFF % 60))
DIFF=$((DIFF / 60))
MIN=$((DIFF % 60))
DIFF=$((DIFF / 60))
HOUR=$((DIFF % 24))
DIFF=$((DIFF / 24))
DAY=$DIFF
echo $DAY days, $HOUR hours, $MIN mins, $SEC seconds ago.