Search code examples
bashshellunixunix-timestamp

Changing date format date -d '180617' +%d-%m-%Y in Shell


I am trying to change the string in date format by using

date -d '180617' +%d-%m-%y

But the output I am getting is

17-06-18

Whereas it should be 18-06-17

Similarly using

  date -d '180617' +%d-%m-%Y

The output is 17-06-2018

Why is it changing day to Year and vice versa?

In my case, Dates in the files are coming in the below format i.e.,date +%d%m%y%H%M%S. As I cannot change the string format for all incoming files.

How can I put the above date in date format.

For example. for the string '150617230001' I want the date as '15-06-2017'


Solution

  • You have misunderstood the option format in date command.

    date -d "format" should be as below:

    date -d "yymmdd"
    

    That is why , Your date becomes year number in your format.

    date -d '170618' +%d-%m-%y
    

    This gives you the right output.

    As far you couldn't change the format in your script,said in comments, here is your needed code.

    date -d `date +%d%m%y%H%M%S | cut -c1-6| sed -E "s/(..)(..)(..)/\3\2\1/g"` +%d-%m-%y
    

    This would change the format after your possibilities..

    18-06-17