Linux Bash 相对日期(x 天前)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4679046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:28:16  来源:igfitidea点击:

Bash relative date (x days ago)

linuxbashdate

提问by Dennis Thrys?e

I have a date string that I am able to parse and format with the datecommand from a bash script.

我有一个日期字符串,我可以date使用 bash 脚本中的命令对其进行解析和格式化。

But how can I determine how many days ago this date was from my script? I would like to end up with a number.

但是我怎么能确定这个日期是多少天前来自我的脚本呢?我想以一个数字结束。

采纳答案by marco

You can do some date arithmetics:

你可以做一些日期算术:

DATE=01/02/2010
echo $(( ( $(date +%s) - $(date -d "$DATE" +%s) ) /(24 * 60 * 60 ) ))

回答by sarnold

Convert your date and now into seconds since the epoch, subtract, divide by the number of seconds in a day:

将您的日期和现在转换为自纪元以来的秒数,减去,除以一天中的秒数:

#!/bin/bash

((a = `date -d "Wed Jan 12 02:33:22 PST 2011" +%s`))
((b = `date +%s`))
echo $(( (b-a) / (60*60*24)))

回答by Andreas WP

Use date itself as date value for date. Example 5 days ago:

使用日期本身作为日期的日期值。5天前的例子:

date -d "`date`-5days"