TransWikia.com

Taking an integer and creating a date format

Unix & Linux Asked by Çağlar Yıldız on December 7, 2020

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?

One 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

Correct answer by glenn jackman on December 7, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP