0

I need to convert a date into a day number and I can use

date +%s --date "10 March 1990"

637027200

To get the second number. Then I divide that number to the number of seconds in a day - 86400

date +%s --date "10 March 1990" / 86400

7373

But it doesn't work for dates before 1 January 1970

and I need to use for dates between 1950 and 2020

Is there any fix for that? Maybe there is some date binary that allows to redefine epoch time to a different date than 1/1/1970 ?

3

2 Answers 2

2

The epoch date is fixed. Since you will need to make ops from 1950 then it's possible for 32 bits Unix time.

Even if the number is negative, you can do an addition of two periods.

From 1950 to 1970 + From 1970 to now :

#Get the current date time timestamp
d1="$(date +%s)"
#Get the timestamp from <date> to 1970 and remove negative sign
d2="$(date +%s --date "10 March 1950" | sed 's/-//g')"
#Perform addition of both timestamps
res="$((d1+d2))"
echo "$res"  # Output 2235228403
2

Another approach: start from 1950, with 0 days before, and just add the number of days for each year as start-off value. How it may look like:

Create array with sum of days for previous years for each year:

#!/bin/bash
ndays[1950]=0
for i in {1951..2020} ; do
    ndays[i]=$(( ${ndays[i-1]}+$(date +%j --date "31 dec $((i-1))" ) ))
done
  

Now your new day ID is just the start value (sum of days for all previous years since 1950) and the day of year of the current date.

date="22 May 1975"
year=$(cut -d' ' -f3 <<<$date)
dayID=$(( ${ndays[year]} + $(date --date "$date" +%-j) ))

(Note: be sure to use %-j and not %j, or else bash will treat the first 99 days of the year as octal values because of the leading 0.)

2
  • This is a good example of why bash should really never be used for anything complex, even though it's fun. Too many traps.
    – mattdm
    Jan 6, 2021 at 17:18
  • @mattdm to be honest: first time I ever heard of the "ocatal trap" - best to stick to bc in the first place.
    – FelixJN
    Jan 6, 2021 at 17:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .