Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a bash string to date format?

I have a bash string 20220416124334 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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 the number of seconds since the epoch, then do it this way:

date -r 1650074146 "+%Y/%m/%d %H:%M:%S"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading