2

I need to convert to date in bash a string which has the hour included, such as: 2012-02-09-18, and store the result inside a variable, so that I can compare such strings as dates. If I use for conversion

  date -d "2012-02-09-18"

it will crash with "Invalid date error". How can I do this?

Crista23
  • 3,203
  • 9
  • 47
  • 60

2 Answers2

4

Try this with bash's parameter expansion:

a="2012-02-09-18"
date -d "${a%-*} ${a#*-*-*-*}"

Output:

Thu Feb  9 18:00:00 CET 2012
Cyrus
  • 84,225
  • 14
  • 89
  • 153
3

You can tweak input to make it parseable by date using sed:

str='2012-02-09-18'

date -d "$(sed 's/-\([^-]*\)$/ \1/' <<< "$str")"
Thu Feb  9 18:00:00 EST 2012
anubhava
  • 761,203
  • 64
  • 569
  • 643