linux bash - 以自定义格式解析日期

标签 linux bash parsing date

我有一个 %c 格式的日期(可以是任何其他格式),我需要在日期命令中使用它。 %c 不是美国格式。它是德国服务器,因为它是德国服务器。这在美国服务器上也无法正常工作。 (区域设置为德语或美国)

这不起作用(包括错误):

user@server:~$ NOW=$(date +%c); echo $NOW
Do 19 Dez 2013 22:33:28 CET
user@server:~$ date --date="$NOW" +%d/%m/%Y
date: ungültiges Datum „Do 19 Dez 2013 22:33:28 CET“

(日期:ungültiges Datum „Do 19 Dez 2013 22:33:28 CET“= 日期:无效日期„Do 19 Dez 2013 22:33:28 CET“)

困难在于我不知道以后会使用哪个语言环境甚至哪个日期格式,因为用户可以设置自己的格式。因此,一个简单的特定解析解决方案并不能真正发挥作用!

但是我该怎么做呢?

概括问题:

如果我有日期格式 format1 (可以是任何一种或至少是一种可以反转的格式) 我可以使用 date 来获取格式化日期。但是,如果我想将其格式化为另一个日期 (format2),我该怎么做呢?
任何使用 coreutils 以外的任何解决方案都是毫无意义的,因为我正在尝试为尽可能多的 unix 机器开发 bash 脚本。

DATE=$(date "+$format1")

date --date="$DATE" "+$format2" # Error in most cases!

这是必需的,因为我有一个用户可以提供日期格式的命令。将显示此日期字符串。但在后面的步骤中,我需要将这个日期字符串转换为另一个固定的日期字符串。我可以操纵命令将获得的 whcih 格式,我可以操纵输出 (或用户将看到的内容)
我无法运行该命令两次,因为它非常耗时。


更新:

我找到了类似的解决方案:

# Modify $user_format so it can be parsed later
user_format="$user_format %s"

# Time consuming command which will print a date in the given format
output=$(time_consuming_command params "$user_format" more params)

# This will only display what $user_format used to be
echo ${output% *}

# A simple unix timestamp parsing ("${output##* }" will only return the timestamp)
new_formated_date=$(date -d "1970-01-01 ${output##* } sec UTC" "+$new_format")

这是有效的,可能对其他人有帮助。所以我将与您分享。

最佳答案

从 GNU coreutils 8.22 开始,--date 是不可能的。来自日期手册:

‘-d datestr’

‘--date=datestr’

Display the date and time specified in datestr instead of the current date and time. datestr can be in almost any common format. It can contain month names, time zones, ‘am’ and ‘pm’, ‘yesterday’, etc. For example, --date="2004-02-27 14:19:13.489392193 +0530" specifies the instant of time that is 489,392,193 nanoseconds after February 27, 2004 at 2:19:13 PM in a time zone that is 5 hours and 30 minutes east of UTC.

Note: input currently must be in locale independent format. E.g., the LC_TIME=C below is needed to print back the correct date in many locales:

date -d "$(LC_TIME=C date)"

http://www.gnu.org/software/coreutils/manual/html_node/Options-for-date.html#Options-for-date

请注意,输入格式不能是特定于语言环境的格式。

可能有其他库或程序可以识别更多的日期格式,但对于给定的日期格式,编写一个简短的程序将其转换为日期可识别的格式(例如,使用 Perl 或 awk)并不困难。

关于linux bash - 以自定义格式解析日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47633398/

相关文章:

c - 以编程方式或来自 procfs 的 netstat 进程名称信息

linux - 防止空格成为for循环bash/shell中的定界符

java - 提高解析文本文件的性能

linux - 获取选择: How to accept arguments that aren't tied to an option in my script?

parsing - flutter/Dart 解析数

parsing - ANTLR Lexer 匹配错误的规则

java - 以可移植的方式以编程方式打开文档

java - 如何运行jar文件取决于jar文件

linux - libssh2_channel_close 将被阻塞,直到远程命令退出

bash - 从 Jenkins 调用时 Tomcat 启动脚本不起作用