Recording and calculating rich elapsed times with Noda Time
Question
I'd like to accurately track key instants for a session object (representing a remote resource), and here is what I would like to do:
- Record key events, such as the session start time
- Display rich time information to the user when asked
- Have the ability to calculate elapsed times between any event, such as the time relative to the session start time
I have some test code where I can successfully gather all of the information that I need, and I'm using IClock
as a basis to start with instants, from which I can create ZonedDateTime
and LocalDateTime
values. I've yet to find any examples other than calculating days and months (using Period
). I need to record and display times (e.g. the elapsed time since the session started) at least down to the second.
Are they any examples like this out there? I searched around and have not found anything yet.
Using the BCL, this would be a job for TimeSpan
. But I want the much richer data provided by Noda Time for a number of reasons (and for consistency in other areas where I am using Noda Time).
Solution
It sounds like you are just looking for the Duration
structure. Something like this?
IClock clock = SystemClock.Instance;
Instant i1 = clock.Now;
// some time later...
Instant i2 = clock.Now;
Duration d = i2 - i1;
You may be able to find more examples by searching Stack Overflow using the nodatime tag.
See also, the core types quick reference in the Noda Time user guide.
If you need something more specific, please edit your question to elaborate. Thanks.