'How to convert a bash string to date format? [duplicate]

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 ?



Solution 1:[1]

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"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1