0

I know the topic has already emerged and some of the posts give a good summary like the one here: Convert string to date in bash . Nevertheless, I encounter a problem presented below with an example I should solve:

date +'%d.%m.%y' works as desired and returns 05.12.20 but the inverse operation I should use to convert strings to date fails:

date -d "05.12.20" +'%d.%m.%y'
date: invalid date ‘05.12.20’

and this is exactly what I need. The Unix date formatting I have also checked on https://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/ but it seems to be in line with that. What is the problem? I also tried to supply time zone indicators like CEST but they did not solve the problem.

Tamas
  • 736
  • 2
  • 11
  • 27

1 Answers1

1

Try

date -d "05-12-20" +'%d.%m.%y'

UNIX date expects either - or / as a date separator.

However, if your input really must be in the format "05.12.20" (i.e. using .), then you can convert it to the format expected by UNIX date:

date -d `echo "05.12.20" | sed 's/\./-/g'` +'%d.%m.%y'
costaparas
  • 5,047
  • 11
  • 16
  • 26
  • My separator is the dot, so the questions is how to get it working with the dot. Anyway, thanks for the response and for reading the post! – Tamas Dec 05 '20 at 10:42
  • Ok, sure, thanks for the clarification. I've updated the answer with a possible alternative that could work for you. – costaparas Dec 05 '20 at 10:50
  • 1
    Warning about "UNIX". `date` can decode also spaces and commas (as the examples in man pages) "and other formats to long to describe in a manual page". Note `-d` is also not in POSIX compatible (and mac has `-f` to handle input format, but non on GNU date) – Giacomo Catenazzi Dec 07 '20 at 10:22