0

Need a string in '9-2-1832' format in a '1832-09-02' format. Must be able to fill a 'date' type field in mysql.

1
  • Can you show us the output of date --version and bash --version?
    – Ryan
    Apr 16, 2016 at 9:34

2 Answers 2

2

If you allow extra tooling (after all you tagged mysql) you could do it with one command from the dateutils package:

$ dateconv -i %m-%d-%Y  "9-2-1832"
1832-09-02

The difference to GNU date is that you can specify the input format using format specifiers (the -i parameter). That way any kind of date can be parsed.

As you wanted standard ISO 8601 formatting as output (the default for all tools from the package) nothing had to be specified there.

Disclaimer: I am the author of dateutils.

1
  • Legend, thank you! This is what I needed.
    – Mint
    Sep 7, 2021 at 8:22
1

Assuming your original date is "month-day-year" (September 2, 1832), something like this might work:

$ date -d $(sed "s/-/\//g" <<< '9-2-1832') +%Y-%m-%d
1832-09-02

Explanation

The date command, even at the current 8.25 version, won't accept a date of the format you list ('9-2-1832', a month-day-year date string with hyphens as separators).

$ date -d '9-2-1832' +%Y-%m-%d
date: invalid date ‘9-2-1832’

But date will accept a month-day-year date string with slashes as separators.

$ date -d '9/2/1832' +%Y-%m-%d
1832-09-02

You can use sed to swap the hyphens for slashes like so.

$ sed "s/-/\//g" <<< '9-2-1832'
9/2/1832

Then you can put the sed command in a subshell to put everything together.

$ date -d $(sed "s/-/\//g" <<< '9-2-1832') +%Y-%m-%d
1832-09-02
3
  • Thanks for the response! Unfortunately, I got this outcome: date -d $(sed "s/-//g" <<< '9-2-1832') +%Y-%m-%d date: invalid date 921832' I also tried it with the escape character: date -d $(sed "s/-/\/g" <<< '9-2-1832')+%Y-%m-%d` sed: -e expression #1, char 7: unterminated s' command date: invalid date +%Y-%m-%d' Apr 16, 2016 at 5:24
  • The command you showed in your comment (date -d $(sed "s/-//g" <<< '9-2-1832') +%Y-%m-%d) is not the same as the one I suggested. It's missing the second parameter for the sed substitution. If you try the correct sed command and that doesn't work, then you'll have to debug a bit. Can you try date -d '9/2/1832' +%Y-%m-%d to make sure that at least that works?
    – Ryan
    Apr 16, 2016 at 9:35
  • You are absolutely right! worked like a charm. Apr 16, 2016 at 14:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .