How to parse a string like 20170202 to a date in a bash script

datefilenames

Say I have several files that are generated by a script and follow the pattern:

yyyymmdd_fileName.fileExtension

And yyyymmdd (i.e. 20170202) is a date, where year is 2017, month is February and day is the 2nd).

I know I can get the complete file name and extract the date part, but how do I make it a date element so I can compare with the current date provided by date?

Best Answer

Use -d arg of date.

man date

   -d, --date=STRING
          display time described by STRING, not 'now'
$ date -d 20170202
Thu Feb  2 00:00:00 CET 2017

To ease the comparsion, you can use the unixdate format

$ date -d 20170203 +%s
1486076400
Related Question