Convert string to date in bash

前端 未结 4 516
挽巷
挽巷 2020-12-08 04:19

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.

\"2

相关标签:
4条回答
  • 2020-12-08 04:39

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

    for OS X, two choices:

    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

    0 讨论(0)
  • 2020-12-08 05:02

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

    date -d '20121212' +'%Y %m'
    
    0 讨论(0)
  • 2020-12-08 05:04

    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'

    0 讨论(0)
  • 2020-12-08 05:04

    We can use date -d option

    1) Change format to "%Y-%m-%d" format i.e 20121212 to 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

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

    3) If we are getting date in some variable say dat

    dat2=$(date -d "$dat -1 days" +'%Y%m%d')
    
    0 讨论(0)
提交回复
热议问题