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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11144408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:30:48  来源:igfitidea点击:

Convert string to date in bash

stringbashshellunixdate

提问by Yahoo-Me

I have a string in the format "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.

我有一个格式为“yyyymmdd”的字符串。它是 bash 中的一个字符串,我想将其转换为日期,以便可以在其上使用所有其他日期函数。

"20121212" string into "20121212" date with format "%Y%m%d".

“20121212”字符串转换为“20121212”日期,格式为“%Y%m%d”。

回答by Nahuel Fouilleul

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'

回答by minhas23

We can use date -d option

我们可以使用 date -d 选项

1) Change format to "%Y-%m-%d" format i.e 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. Like get a date 7 days in past with specific format

2)从给定日期获取下一天或最后一天=20121212。就像使用特定格式获取过去 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')

回答by Vanjor

date only work with GNU date (usually comes with Linux)

date 仅适用于 GNU date(通常与 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

  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

  1. 更改命令(已验证)

    #!/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

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

回答by johnshen64

just use the -d option of the date command, e.g.

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

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