2

I am trying to dynamically convert one column in text file containing date in dd/mm/yyyy hh:mm:ss format to yy-mm-dd hh:mm:ss. Following command is working but giving output in yy-dd-mm and NOT yy-mm-dd as I need.

echo $(date -d "8/11/2018 06:20:57 AM" "+%y-%m-%d %H:%M:%S")

Output:

18-08-11 06:20:57

Moreover, this is not working for dates > 12 as it is treating first digit as month not date as below:

echo $(date -d "28/11/2018 06:20:57 AM" "+%y-%m-%d %H:%M:%S")

Output:

date: invalid date ‘28/11/2018 06:20:57 AM’

Is there any way to make it work?

3
  • 2
    date is very flexible on the output but the input is very specific. I'd suggest to transform the date before reaching date. May be bring in them from SQL functions or Javascript (depending on the source). If there is no source (like from a file), I'd suggest sed or awk
    – Juan
    Commented Mar 25, 2019 at 23:15
  • ... or use something like Perl's Time::Piece with its strptime/strftime implementations Commented Mar 25, 2019 at 23:26
  • or php -r "command" ...
    – Juan
    Commented Mar 25, 2019 at 23:29

2 Answers 2

1

You might want to pre processes it first. My best shot is with sed

echo "28/11/2018 06:20:57 PM" | sed -E "s/([0-9]+)\/([0-9]+)\/([0-9]+) ([0-9]+):([0-9]+):([0-9]+) ([APM]{2})/\3\/\2\/\1 \4:\5:\6 \7/g" | xargs -I II date -d II "+%y-%m-%d %H:%M:%S"

0
0

How about:

DATE=$(echo "28/11/2018 06:20:57 PM" | awk -F'/' 'OFS="/" {print $2,$1,$3}') # equals "11/28/2018 06:20:57 PM"
date -d "${DATE}" "+%y-%m-%d %H:%M:%S" # returns "18-11-28 18:20:57"

You must log in to answer this question.

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