Reputation: 3243
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?
Upvotes: 2
Views: 297
Reputation: 88601
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
Upvotes: 4
Reputation: 785146
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
Upvotes: 3