How can I change the format of a date from the command line?

后端 未结 6 1549
梦毁少年i
梦毁少年i 2020-12-19 17:04

What\'s the quickest way to convert a date in one format, say

2008-06-01

to a date in another format, say

相关标签:
6条回答
  • 2020-12-19 17:29
    $ date -d '2005-06-30' +'%a %F'
    Thu 2005-06-30
    

    See man date for other format options.

    This option is available on Linux, but not on Darwin. In Darwin, you can use the following syntax instead:

    date -j -f "%Y-%m-%d" 2006-06-30 +"%a %F"
    

    The -f argument specifies the input format and the + argument specifies the output format.

    As pointed out by another poster below, you would be wise to use %u (numeric day of week) rather than %a to avoid localization issues.

    0 讨论(0)
  • 2020-12-19 17:39

    Reading the date(1) manpage would have revealed:

    -j   Do not try to set the date.  This allows you to use the -f flag
         in addition to the + option to convert one date format to another.
    0 讨论(0)
  • 2020-12-19 17:40

    Thanks for that sgm. So just so I can come back to refer to it -

    date -j -f "%Y-%m-%d" "2008-01-03" +"%a%e %b %Y"
                ^               ^        ^
                parse using     |        output using
                this format     |        this format
                                |
                           date expressed in
                           parsing format
    
    Thu 3 Jan 2008
    

    Thanks.

    0 讨论(0)
  • 2020-12-19 17:43

    If you're just looking to get the day of the week, don't try to match strings. That breaks when the locale changes. The %u format give you the day number:

     $ date -j -f "%Y-%m-%d" "2008-01-03" +"%u"
     4
    

    And indeed, that was a Thursday. You might use that number to index into an array you have in your program, or just use the number itself.

    See the date and strftime man pages for more details. The date manpage on OS X is the wrong one, though, since it doesn't list these options that work.

    0 讨论(0)
  • 2020-12-19 17:45
    date -d yyyy-mm-dd
    

    If you want more control over formatting, you can also add it like this:

    date -d yyyy-mm-dd +%a
    

    to just get the Sun part that you say you want.

    0 讨论(0)
  • 2020-12-19 17:53
    date -d ... 
    

    doesn't seem to cut it, as I get a usage error:

    usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
                [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
    

    I'm running GNU bash, version 3.2.17(1)-release (i386-apple-darwin9.0), and as far as the man goes, date -d is just for

    -d dst  Set the kernel's value for daylight saving time.  If dst is non-
             zero, future calls to gettimeofday(2) will return a non-zero for
             tz_dsttime.
    
    0 讨论(0)
提交回复
热议问题