Taking an integer and creating a date format

I can take a date and convert is to an integer.

date_as_integer = $("2020-06-13" | sed "s/-//g") 

However is there a way to convert it back to date?

Answer

Doing it with string manipulation using bash parameter expansion:

date2int() {
  printf "%sn" "${1//-/}"
}

int2date() {
  printf "%s-%s-%sn" "${1:0:4}" "${1:4:2}" "${1:6:2}"
}

date +%F                                # => 2020-07-24
n=$(date2int "$(date +%F)"); echo "$n"  # => 20200724
d=$(int2date "$n"); echo "$d"           # => 2020-07-24

This technique is definitely NOT OK for date arithmetic.

# subtract 2 days from Jan 1
date="2000-01-01"
n=$(date2int "$date")
int2date "$((n - 2))"          # => 2000-00-99

You might as well stick to GNU date

date="2000-01-01"
date -d "$date - 2 day" "+%F"  # => 1999-12-30

Leave a Reply

Your email address will not be published. Required fields are marked *