1

I'm getting a date in the format of

    v_date=$(date +"%Y%m%d" -d "1970-01-01 + $(stat -c '%Z' file ) secs")
    v_sysdate=$(date +%Y%m%d)
echo "$v_date"

20150907

echo "$v_sysdate"

20150907

v_date_difference=$((${v_sysdate}-${v_date}))
echo "$v_date_difference"

The value returned is -20150907, but it should be zero.

How can I get the difference between the dates in whole days?

  • this is not an answer, any reason tou don't use stat -c '%Y%m%d' ? – Archemar Sep 7 '15 at 13:12
  • I want to compare with sysdate to find how old by the number of days – VRVigneshwara Sep 7 '15 at 13:23
  • 3
    echo $(( ($(date +%s) - $(stat -c '%Z' file )) / 86400 )) – Archemar Sep 7 '15 at 13:32
  • What do you mean by "The value returned is -20150907, but it should be zero." ? – Thomas Erker Sep 7 '15 at 22:02
2

You can't subtract two dates written in a YYYYMMDD format. For example 20150907 - 20140907 obviously yields 10000 instead of 365.

20150907 - 20150907 does yield 0 — it's a valid way to test for equality, except that you could just test equality directly instead of calculating the subtraction. If you're getting -20150907, it's because the code isn't what you showed, and v_sysdate contains extra characters (other than whitespace and digits).

The sane way to manipulate dates is to convert them into a simple numeric format: number of time units since a fixed origin (an epoch). In the Unix world, the standard unit is seconds (like in SI) and the epoch is 1970-01-01.

GNU utilities such as date and stat print dates in seconds since the epoch with the %s format. Use this format until you need to pretty-print it. To pass date a date in this format, put @ before the number of seconds.

v_date=$(stat -c '%Z' file)
v_sysdate=$(date +%s)
v_date_difference=$((v_sysdate-v_date))
date -d "@$v_date" +'File ctime: %Y%M%D'
date -d "@$v_sysdate" +'Current time: %Y%M%D'
echo "$v_date_difference seconds elapsed"
echo "$((v_date_difference / 86400)) days elapsed"

Note that this calculates the number of days between the two times. For example, between yesterday 23:59 and today 00:01, this shows a difference of 0 days. If you need the difference between two dates, ignoring the time of day, you can use a reference time during the day.

file_midday_time=$(date +%s -d "$(date '+%Y-%m-%d 12:00' -d "@$(stat -c %Z file)")")
current_midday_time=$(date +%s -d "today 12:00")
day_difference=$(((file_midday_time - current_midday_time + 7200) / 86400))

Adding a number between 3601 and 86399 ensures that one day is accounted for even on the day clocks switch from normal time to daylights saving time (that day only lasts 23 hours).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.