在 bash 中获取自定义日期值的 EPOCH 时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14461247/
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-09-18 04:19:52  来源:igfitidea点击:

Getting the EPOCH time for a custom date values in bash

bash

提问by lukegjpotter

I need to write a bash function to return the EPOCH time for a custom date, in the future.

我需要编写一个 bash 函数,以便将来返回自定义日期的 EPOCH 时间。

I use date and time in the formats;

我在格式中使用日期和时间;

date=20130122 # i.e. 2013 01 22
time=1455     # i.e. 14:55

Can I get the EPOCH time with these values?

我可以使用这些值获得 EPOCH 时间吗?

Does anyone know a solution?

有谁知道解决方案?

回答by Hari Menon

date -d "$date $time" +%s

Would work in GNU date.

将在 GNU 日期工作。

For BSD date(included with Mac OS X), the command would be

对于 BSD date(包含在 Mac OS X 中),命令将是

date -j -f "%Y%m%d %H%M" "$date $time" +%s

(-fis needed to parse your date and time as given; the default format would require "012214552013" to specify the same time)

-f需要解析给定的日期和时间;默认格式需要“012214552013”​​来指定相同的时间)

回答by Eigir

Short answer:

简答:

date --date "20130122 1455" +%s

This will give you the date in epoch.

这将为您提供纪元的日期。

Or if you use variables, just replace the date and time like this:

或者,如果您使用变量,只需像这样替换日期和时间:

d=20130122
t=1455
date --date "$d $t" +%s

And try to avoid using "date" and "time" as variable names, since they easily could be misunderstood as commands (they are both valid commands). This to increase readability.

并尽量避免使用“日期”和“时间”作为变量名,因为它们很容易被误解为命令(它们都是有效命令)。这是为了增加可读性。

回答by linuph

Stumbled upon this one. In BASH 3.2 I get an 'invalid date' error. Should be:

偶然发现了这个。在 BASH 3.2 中,我收到“无效日期”错误。应该:

date -d "2013-01-22 14:55" +%s