在 bash 中转换日期格式 [英] Convert date formats in bash

查看:43
本文介绍了在 bash 中转换日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式为27 JUN 2011"的日期,我想将其转换为 20110627

I have a date in this format: "27 JUN 2011" and I want to convert it to 20110627

可以用 bash 做吗?

Is it possible to do in bash?

推荐答案

#since this was yesterday
date -dyesterday +%Y%m%d

#more precise, and more recommended
date -d'27 JUN 2011' +%Y%m%d

#assuming this is similar to yesterdays `date` question from you 
#http://stackoverflow.com/q/6497525/638649
date -d'last-monday' +%Y%m%d

#going on @seth's comment you could do this
DATE="27 jun 2011"; date -d"$DATE" +%Y%m%d

#or a method to read it from stdin
read -p "  Get date >> " DATE; printf "  AS YYYYMMDD format >> %s"  `date
-d"$DATE" +%Y%m%d`    

#which then outputs the following:
#Get date >> 27 june 2011   
#AS YYYYMMDD format >> 20110627

#if you really want to use awk
echo "27 june 2011" | awk '{print "date -d""$1FS$2FS$3"" +%Y%m%d"}' | bash

#note | bash just redirects awk's output to the shell to be executed
#FS is field separator, in this case you can use $0 to print the line
#But this is useful if you have more than one date on a line

更多关于日期

注意这仅适用于 GNU 日期

note this only works on GNU date

我读过:

Solaris 版本的日期,无法支持 -d 可以解决替换 sunfreeware.com 版本的日期

Solaris version of date, which is unable to support -d can be resolve with replacing sunfreeware.com version of date

这篇关于在 bash 中转换日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆