AnswerBun.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!

Related Questions

Debian Buster Can not set static IP

1  Asked on December 15, 2021 by cstrutton

     

Restore Default Super Key Behavior (xkbmap)

2  Asked on December 15, 2021 by silvio-mayolo

     

iptables – How to allow all connections to the local lan?

2  Asked on December 12, 2021 by adrelanos

 

Hard Disk Space for Debian 10

2  Asked on December 12, 2021 by user423440

       

Trouble setting ports for forwarding

1  Asked on December 12, 2021 by kekearifzzz

 

Accessing a legacy NFS

1  Asked on December 12, 2021 by willie-mckemie

 

Need to get average waiting time for a month

2  Asked on December 12, 2021 by shiwangini-shishulkar

   

fine grain sudo permission not working

2  Asked on December 12, 2021

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir