从参数创建一个 bash 日期/时间变量

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

Create a bash date/time variable from argument

bashdatetimebsd

提问by David

Given an argument being passed in like this:

给定一个像这样传入的参数:

~/Documents/checkout/check-out.sh potatoes '2013/05/22 13:43:00'

Using 1st or 2nd line, produces

使用第一行或第二行,产生

st=`date --date "" +%s`                   # mogul's suggestion
st=$(date --date="" +%s)                  # Kent's suggestion
st=$(date --date="2013/05/22 14:45:00" +%s)

date: illegal option -- -
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
    [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

回答by Gordon Davisson

OS X's version of datedoesn't understand the --dateoption; you need to use -fand give it the format of the input date:

OS X 的版本date不理解该--date选项;您需要使用-f并为其指定输入日期的格式:

st=$(date -j -f "%Y/%m/%d %T" "" +%s)

For example:

例如:

$ date -j -f "%Y/%m/%d %T" "2013/05/22 14:45:00" +%s
1369259100

回答by Adrian Frühwirth

Your OSX ships with a BSD date, not GNU date, so there are no GNU-style options (you can install GNU datevia macports or homebrew).

您的 OSX 附带BSD date, not GNU date,因此没有 GNU 风格的选项(您可以GNU date通过 macports 或自制软件安装)。

回答by mogul

x='2013/05/22 13:43:00'
st=`date --date "$x" +%s`

seems to work here. or in your case it should be

似乎在这里工作。或者在你的情况下应该是

st=`date --date "" +%s`

回答by Kent

try this:

尝试这个:

st=$(date --date="" +%s)