I need to calculate the elapsed time (nicely formatted) between now and a file’s last modification date/time, ie. something like this, only in my case, the difference can be in days, months or even years.
I tried this:
var
TimeDiff : Double;
begin
TimeDiff := Now - FileAgeEx('C:\my-file.txt');
if (TimeDiff >= 1) then
Caption := FormatDateTime('dd hh:nn:ss', TimeDiff)
else
Caption := FormatDateTime('hh:nn:ss', TimeDiff);
end;
But (1) it doesn’t work and (2) I’d like a better formatting.
Ultimately my goal is to have something like this:
- Time Diff < 1 day ==> display this: 12:00:01
- Time Diff >= 1 day ==> display this: 25 days, 12:00:01
- Time Diff >= 1 year ==> display this: 2 years, 3 months, 10 days, 12:00:01
Anyone knows how can I do that?
Thanks!
The main problem would appear to be getting hold of the last modified time of the file. I use the following code:
You call
LastWriteTimeto get the last modified time in file time format. Then callUTCFileTimeToDateTimeto convert intoTDateTimeaccounting for the prevailing local time zone of the machine. You can then compare that value withNow.As regards the formatting, you already appear to know how to do that. You basic approach will work and you just need to flesh out the details.
In the comments you say that
shows a
1for the day when you would expect a2. The problem is that this function formats dates rather than time intervals. The value2.9is not treated as an elapsed time, rather it is treated as an absolute date/time,2.9days after the Delphi epoch. I would useTruncandFracto obtain number of days, and the part of days respectively, and work from there.The following code, extracted directly from my codebase, may give you some pointers. Note that its input is in seconds, but it should set you on the right path.