Bash script need to convert string to date

11,265

The date command is quite flexible in recognizing strings that represent dates. So, for example:

$ date -d 'Oct 29 2018'
Mon Oct 29 00:00:00 CET 2018

The -d flag instructs date to display the date given to it as a string.
You can add the +FORMAT parameter to convert the date as you like. For example:

$ date -d 'Oct 29 2018' '+%Y-%m-%d'
2018-10-29

Refer to man date for the option you have to set the output format.

EDIT:

Sorry, I didn't get your reference to -mtime. Are you talking about the find filter? If so, I guess you need the difference between today and your OLDEST_DATE, in days.

You can obtain it by converting dates to the Epoch format (seconds since 1970-01-01 00:00:00 UTC). For example:

$ current="$(date '+%s')"
$ oldest_date_epoch="$(date -d "$OLDEST_DATE" '+%s')"
$ diff_days=$(( ("$current" - "$oldest_date_epoch") / (3600 * 24) ))

Note this is not a general solution, since date cannot understand foreign languages.

Share:
11,265

Related videos on Youtube

stefzeer
Author by

stefzeer

Updated on September 18, 2022

Comments

  • stefzeer
    stefzeer over 1 year

    Hello I have this bash script for checking the integrity of backups. I need to edit it as I have to make warn me when the oldest backup is more than 60 days (as we delete those).

    Now the date is extracted from another file

    OLDEST_DATE=`cat /tmp/B_BACKUP_TMP.out | head -1  | cut -f5,6,8 -d" "`
    

    in the following format :

    Oct 29 2018

    However, this format can't get picked up when I try to use it with -mtime +60

    Any ideas how I can convert it ?

    Thank you.