How to change the date format from the command line?

What is the fastest way to convert a date to one format, say

2008-06-01

up to a date in a different format, say

Sun 1 June 2008

An important bit is the “Sun”, because, depending on the name of the day, I may need to mess with other things - in a non-deterministic style. I am running GNU bash, version 3.2.17 (1) -release (i386-apple-darwin9.0).

[Background: The reason I want to do this from the command line is because I really want to write it to the TextMate ... This is an annoying task that I have to do all the time in textMate. ]

+4
source share
6 answers
$ date -d '2005-06-30' +'%a %F' Thu 2005-06-30 

See man date for other format options.

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

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

The -f argument indicates the input format, and the + argument indicates the output format.

As indicated by another poster below, it would be wise for you to use% u (the numeric day of the week) rather than% a to avoid localization problems.

+8
source

Reading the date (1) man page would show:

  -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 . 
+1
source

Thanks for this sgm. Therefore, so that I can return to turn to him -

 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.

+1
source
 date -d yyyy-mm-dd 

If you want more control over formatting, you can also add it as follows:

 date -d yyyy-mm-dd +%a 

just to get the part of the sun that you want to say.

0
source
 date -d ... 

doesn't seem to abbreviate 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 am running GNU bash, version 3.2.17 (1) -release (i386-apple-darwin9.0), and as far as a person goes, date -d is only for

 -d dst Set the kernel value for daylight saving time. If dst is non- zero, future calls to gettimeofday(2) will return a non-zero for tz_dsttime. 
0
source

If you just want to get the day of the week, do not try to match the strings. It breaks when the locale changes. The %u format gives you the day number:

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

And indeed, it was Thursday. You can use this number to index into the array that you have in your program, or just use the number.

See the date and strftime man pages for more information. However, the date man page in OS X is incorrect because it does not display these options that work.

0
source

All Articles