2014-06-12 128 views
0

说我有以下格式为我的日期输出:解析非标准日期格式

date --utc +%d.%m.%Y,\ %H:%M\ UTC 
# Outputs: 12.06.2014, 09:03 UTC 

如何显示输出的日期上面,在另一个date号召,另一种格式?我想:

date --utc --date="12.06.2014, 09:03 UTC" +%d.%m.%Y,\ %H:%M\ UTC 

,但没有成功(它说invalid date)。

我主要试图做到这一点,以便能够从输出日期知道已经过了多少小时(或者几天,或者任何时间的测量单位)。

+1

只需删除逗号,并用斜线替换点:'日期-utc +%d /%m /%Y \%H:%M \ UTC'。 – fedorqui

+0

您可以在'bsd date'中指定自定义日期格式,但不能在'gnu'中。 – BroSlow

回答

2

这里是man date页说,大约为​​选项格式是什么:

The --date=STRING is a mostly free format human readable date string such as 
"Sun, 29 Feb 2004 16:21:42 -0800" or "2004-02-29 16:21:42" or even "next 
Thursday". A date string may contain items indicating calendar date, time of day, 
time zone, day of week, relative time, relative date, and numbers. An empty 
string indicates the beginning of the day. The date string format is more 
complex than is easily documented here but is fully described in the info 
documentation. 

因此,你可以使用,例如:

date --date "2014-06-12 09:03 UTC" --utc +%d.%m.%Y,\ %H:%M\ UTC 
# Output: 12.06.2014, 09:03 UTC 

得到你的愿望。

你可以从你的第一输出很容易得到这一第二种形式与sed线如下:

sed 's/\([0-9]\{2\}\)\.\([0-9]\{2\}\)\.\([0-9]\{4\}\), \(.*\)/\3-\2-\1 \4/' 
    <<< '12.06.2014, 09:03 UTC' 
# Output: 2014-06-12 09:03 UTC 

注意,它可能会更快地输出日期在ISO 8601的格式在第一时间进行再利用,例如与:

date --utc +%F\ %H:%M\ UTC 
# Output: 2014-06-12 10:12 UTC 
+1

关于ISO 8601的进一步阅读:http://xkcd.com/1179/ – Qeole

+0

我可能没有和你一样的'date'版本。因此我无法执行上述操作。 – linkyndy

+0

@AndreiHorak你是说,我写的第一个'date'命令(以'--date“2014-06-12 09:03 UTC”'为输入)?我使用'date(GNU coreutils)8.20'。不知道你的版本是什么('$ date --version'),并且可能有什么区别:/ – Qeole

1

我认为你不能指定输入格式,所以你必须有这样的另一个命令来改变它:

date --utc --date="$(echo "12.06.2014, 09:03 UTC" | sed -r 's/(..).(..).(....), (..):(..) UTC/\3-\2-\1 \4:\5 UTC/')" 

此外,如果你想arithmethic在此,你可以使用+%s

DATE1=$(date "+%s" --date="$(echo "12.06.2014, 09:03 UTC" | sed -r 's/(..).(..).(....), (..):(..) UTC/\3-\2-\1 \4:\5 UTC/')") 
DATE2=$(date "+%s" --date="$(echo "17.06.2014, 08:30 UTC" | sed -r 's/(..).(..).(....), (..):(..) UTC/\3-\2-\1 \4:\5 UTC/')") 
DIFF_IN_SECONDS=$(($DATE2-$DATE1)) 
DIFF_IN_RAW_DAYS=$((($DATE2-$DATE1)/86400)) 
DIFF_IN_DATES=$(((($DATE2/86400) - ($DATE1/86400))))