如何预设一段时间'之前'(从现在开始的相对时间)

时间:2014-01-07 22:49:52

标签: bash command-line date-formatting

如何显示给定日期的持续时间。例如:

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

或类似的东西。关键是当它包含在句子中时应该很容易理解。

(这不是仅仅指定整天的this question的副本。)

2 个答案:

答案 0 :(得分:1)

今天我遇到了类似的问题,最终为此编写了一个函数:

 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

如果要评论/编辑,它可以作为a gist使用。间隔是受rails' distance_of_time_in_word启发的。

答案 1 :(得分:0)

您可以使用一些模块化算法来完成此任务。例如:

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.