This answer is wrong!!! The difference should be calculated manually from the number of seconds. Displaying with date
command just displays month, day number of the day, which is so many seconds from 1970-01-01
.
I would do it like this:
#!/bin/bash
d1=$(date -d "$(stat / | grep "Birth" | sed 's/Birth: //g')" +%s)
d2=$(date +%s)
date -d "@$(($d2 - $d1))" +'%m months, %d days, %H hours'
Get both times in seconds. Subtract them and display them in a format of your choice. In this case it is in months, days and hours. You can change that to your preferences. Try man date
to see what options you have for output format.
Regarding confusion in date format YYYY-MM-DD, I have never seen that computer would interpret that wrongly as YYYY-DD-MM.
Addition based on muru's comment (oneliner):
date -d "@$(($(date +%s) - $(stat / --format %W)))" +'%m months, %d days, %H hours'
Addition after @Saeed Neamati comment. The following answers provide much better solutions. They are still not 100% correct.
First option
If you calculate difference and then add that difference to 1970-01-01, you can display the difference in years, months and day from 1970-01-01. Because months differ in length and because of leap years the result is not exact:
seconds=$(date -d "@$(($(date +%s) - $(stat / --format %W)))" +%s)
years=$(($(date -d @$seconds +%Y) - 1970))
months=$(($(date -d @$seconds +%m) - 1))
days=$(($(date -d @$seconds +%d)))
echo $years years, $months months, $days days
Second option
Another way is to get both dates and calculate the difference between them. Days may not be correct, because not all months are 31 days long:
d1_year=$(date -d @$(stat / --format %W) +%Y)
d1_month=$(date -d @$(stat / --format %W) +%-m)
d1_day=$(date -d @$(stat / --format %W) +%-d)
d2_year=$(date +%Y)
d2_month=$(date +%-m)
d2_day=$(date +%-d)
years=$(($d2_year - $d1_year))
months=$(($d2_month - $d1_month))
if (( $months < 0 )); then
months=$(($months + 12))
years=$(($years - 1))
fi
days=$((d2_day - $d1_day))
if (( $days < 0 )); then
days=$(($days + 31))
months=$((months -1))
fi
echo $years years, $months months, $days days
stat /
I getBirth: -
confused, don't know about stat but interested in finding date of linux installation. – ron Jan 23 '23 at 15:50date
command or something similar, you would want to convert that to epoch time which will be a long int of seconds since 1970 (way back) then do simple subtraction to get elapsed time, then scale seconds to number of days. The C library time.h has those functions – ron Jan 23 '23 at 15:53