linux - 如何将字符串转换为特定格式的日期时间?

标签 linux bash datetime

我看不到任何方法来指定日期的解析格式,并且我的输入格式无法识别:

dt1=`date --date="20151020T113100.475"`; echo $dt1  # fails with 'invalid date'

最佳答案

根据 DevSolar 的建议,如果您没有使用这些值进行任何其他日期处理,则可以使用

if [[ $dt1 < $dt2 ]]; then
  # your logic here..
  printf "less than..\n";
else
  # your logic here..
  printf "greater than or equal..\n";
fi

如果您需要将这些转换为日期形式和/或想要验证字符串输入,可以使用 bash 子字符串提取:

$ dt1="20151020T113100.475"
$ date -d "${dt1:0:4}-${dt1:4:2}-${dt1:6:2} ${dt1:9:2}:${dt1:11:2}:${dt1:13:6}"
Tue Oct 20 11:31:00 AEDT 2015

输出格式也可以在这里应用,例如:

$ date -d "${dt1:0:4}-${dt1:4:2}-${dt1:6:2} ${dt1:9:2}:${dt1:11:2}:${dt1:13:6}" +"%s"
1445301060

此处 %s 给出自 1970-01-01 00:00:00 UTC 以来的秒数

因此,要与另一个日期(dt2)进行比较,可以使用类似的内容

dt1="20151020T113100.475"
dt2="20151021T113100.475"
ts1=$(date -d "${dt1:0:4}-${dt1:4:2}-${dt1:6:2} ${dt1:9:2}:${dt1:11:2}:${dt1:13:6}" +"%s")
ts2=$(date -d "${dt2:0:4}-${dt2:4:2}-${dt2:6:2} ${dt2:9:2}:${dt2:11:2}:${dt2:13:6}" +"%s")
if ((ts1<ts2)); then
  # your logic here..
  printf "less than..\n"
else
  # your logic here..
  printf "greater than or equal..\n"
fi

输出

less than..

参见man date 有效的输出格式

关于linux - 如何将字符串转换为特定格式的日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236050/

相关文章:

linux - awk - 根据错误代码查找排名靠前的 url

linux - 在 bash 中交换两个文件的最短方法

linux - 使用标准 shell 构建自定义应用程序特定的 shell

linux - 为什么我不能用这个循环从 bash 历史记录中删除多个条目

python - 如何在 Pandas 中读取带时区的日期时间

c++ - 如何让我的 makefile 覆盖一个文件?

c - 我的进程仍然是守护进程吗?

bash - 覆盖 git clone 的 bash 补全

postgresql - 无法从时间戳 Postgres 中提取时间

Django 1.6 按小时和时区过滤问题