0

I have a bash string 20220416124334 (the string is not epoch) and I want to convert it to date format so it should look like this: 2022/04/16 12:43:34

I've tried:

[manjaro@manjaro ~]$ date -d '20220416124334' "+%Y/%m/%d %H:%M:%S"
date: invalid date ‘20220416124334’

How should I do it correctly ?

Joe
  • 791
  • 1
  • 9
  • 24
  • `date -d '20220416 1243' "+%Y/%m/%d %H:%M:%S" ` does work, fwiw. Space between date and time, and no seconds. – Shawn Apr 16 '22 at 04:42
  • @Shawn this is the worst answer so far, you got rid of the `second` part from the string. – Joe Apr 16 '22 at 08:27

1 Answers1

0

I would expect to use the date command, as you employ it, with a number that represents the number of seconds since the epoch. It seems your number is a formatted date yyyymmddhhmiss.

If you don't need to validate the string that represents a formatted date, then you can use sed to insert extra formatting characters:

echo '20220416124334' | sed -E 's/(....)(..)(..)(..)(..)(..)/\1\/\2\/\3 \4:\5:\6/'

If you end up taking as input a number of seconds since the epoch, then do it this way, keeping in mind that a number means different times in different time zones at different times of the year (eyeroll):

date -u -r 1650113014 "+%Y/%m/%d %H:%M:%S"
Jeff Holt
  • 2,940
  • 3
  • 22
  • 29