1

I want to convert a String in %m%d%Y format to date.

But, getting invalid date error as shown below:

bash-4.1$ date -d '10042015' +"%m%d%Y"
date: invalid date `10042015'

How to fix it?

3
  • 2
    Should be 20151004 or 10/04/2015
    – Costas
    Commented Oct 15, 2015 at 11:00
  • Does it mean, in shell script only these 2 formats are supported? It seems strange to me. In this case, how shall I convert 10042015 string into date? Commented Oct 15, 2015 at 11:06
  • or read man bash and look for Substring Expansion
    – X Tian
    Commented Oct 15, 2015 at 11:41

1 Answer 1

3

The date + option sets only the output format, not the input. You'll need to use a different tool or format the string first:

date --date="$(sed 's/^\([0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9][0-9][0-9]\)$/\3-\1-\2/' <<< '10042015')"

or

date --date="$(sed 's/\(..\)\(..\)\(....\)/\3-\1-\2/' <<< '10042015')"

or simply

date --date="$(sed 's/\(.*\)\(....\)$/\2\1/' <<< '10042015')"

(thanks @Costas). Even though the last two are shorter I would still suggest the first one, because:

  1. it's stricter, avoiding strange bugs if handling strings from third party tools or users, and, more importantly,
  2. it's more maintainable, since it's more obvious what the code is doing (rearranging three numbers and putting hyphens between them as opposed to moving the last four characters to the start of the string).
1
  • The OP use %m%d%Y format so sed 's/\(.*\)\(....$\)/\2\1/' is enough
    – Costas
    Commented Oct 15, 2015 at 12:19

You must log in to answer this question.

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