How to convert from one date format to other format?

94,559

Solution 1

Use GNU 'date' for this. It will also convert between other formats for you (see date --help for the list of formats).

$ date -d 2013-07-05 +%m/%d/%Y
07/05/2013
$ date -d 07/05/2013 +%F
2013-07-05

Solution 2

Assuming you have dates in text form that need to be converted

echo '2013-12-13' | awk -v FS=- -v OFS=/ '{print $2,$3,$1}'

And vice-versa

echo '12/13/2013' | awk -v FS=/ -v OFS=- '{print $3,$1,$2}'

Solution 3

$ echo YYYY-MM-DD | { IFS=- read y m d && echo "$m/$d/$y"; }
MM/DD/YYYY

If you have a file with a lot of those dates, one per line:

awk -F- -vOFS=/ '{print $2,$3,$1}' < that-file

Solution 4

Answering the clarified question in the comments about how to change the date format in a filename, use a variant of drewbenn's gnu date approach. This command finds all files in the local folder, and pipes only the file name to xargs, substituting the date modified filename as the second argument to mv which performs the rename.

The additional, slightly circuitous use of bash variable substitution is necessary as bash evaluates the date command.

find ./ -printf '%f\n' | xargs -I '{}' sh -c 'mv $1  $(date -j -f %Y-%m-%d $1 +%m/%d%Y)' -- {} \;
Share:
94,559

Related videos on Youtube

AiB
Author by

AiB

Updated on September 18, 2022

Comments

  • AiB
    AiB over 1 year

    I have one problem with my date format. I want to change from one format to the other and vice versa. My date formats are

    Format 1

    YYYY-MM-DD
    

    Format 2

    MM/DD/YYYY
    

    I want to change format 1 to format 2 and format 2 to format 1 .

    • AiB
      AiB over 10 years
      o be more clear, I have the file file1 name: date 2000-01-01 2000-01-02 2000-01-03 2000-01-04 .. Required output is 01/01.2000 01/02/2000 01/03/2000 01/02/2000 and vice versal
    • evilsoup
      evilsoup over 10 years
      Forward-slashes are one of the only two characters that cannot be in a *nix filename...
  • AiB
    AiB over 10 years
    to be more clear, I have the file file1 name: date 2000-01-01 2000-01-02 2000-01-03 2000-01-04 .. Required output is 01/01.2000 01/02/2000 01/03/2000 01/02/2000 and vice versal
  • AiB
    AiB over 10 years
    to be more clear, I have the file file1 name: date 2000-01-01 2000-01-02 2000-01-03 2000-01-04 .. Required output is 01/01.2000 01/02/2000 01/03/2000 01/02/2000 and vice versal
  • jordanm
    jordanm over 10 years
    @Abraham how does this not meet that requirement?
  • AiB
    AiB over 10 years
    Thank you 1_CR, It is working now after I modified a little bit!! #!/bin/bash echo '$1-$2-$3' | awk -v FS=- -v OFS=/ '{print $2,$3,$1}' data.file
  • Mathias Begert
    Mathias Begert over 10 years
    @Abraham, you should try your luck with drewbenn's date approach, that is certainly more elegant