简体   繁体   English

在bash中将字符串转换为日期

[英]Convert string to date in bash

I have a string in the format "yyyymmdd". 我有一个格式为“yyyymmdd”的字符串。 It is a string in bash and I want to get it converted into a date so that all other date functions can be used on it. 它是bash中的一个字符串,我希望将其转换为日期,以便可以在其上使用所有其他日期函数。

"20121212" string into "20121212" date with format "%Y%m%d". “20121212”字符串转换为“20121212”日期,格式为“%Y%m%d”。

This worked for me : 这对我有用:

date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'

then you can format output adding parameter '+%Y%m%d' 然后你可以格式化输出添加参数'+%Y%m%d'

We can use date -d option 我们可以使用date -d选项

1) Change format to "%Y-%m-%d" format ie 20121212 to 2012-12-12 1)将格式更改为“%Y-%m-%d”格式,即20121212至2012-12-12

date -d '20121212' +'%Y-%m-%d'

2)Get next or last day from a given date=20121212. 2)从给定日期= 20121212获取下一天或最后一天。 Like get a date 7 days in past with specific format 比如使用特定格式获取过去7天的日期

date -d '20121212 -7 days' +'%Y-%m-%d'

3) If we are getting date in some variable say dat 3)如果我们在一些变量说dat的日期

dat2=$(date -d "$dat -1 days" +'%Y%m%d')

date only work with GNU date (usually comes with Linux) 日期仅适用于GNU日期(通常附带Linux)

for OS X, two choices: 对于OS X,有两种选择:

  1. change command (verified) 更改命令(已验证)

     #!/bin/sh #DATE=20090801204150 #date -jf "%Y%m%d%H%M%S" $DATE "+date \\"%A,%_d %B %Y %H:%M:%S\\"" date "Saturday, 1 August 2009 20:41:50" 

    http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html

  2. Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html 从Coreutils下载GNU实用程序 - GNU核心实用程序(尚未验证) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html

只需使用date命令的-d选项,例如

date -d '20121212' +'%Y %m'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM