DEV Community

Brandon Weaver
Brandon Weaver

Posted on

An Easy Way to Calculate Duration in C#

For a project I'm currently working on, I needed to find a simple way to calculate the duration between two button presses. I considered using the stopwatch, or timer class, but I discovered a (in my opinion) better solution.

public void OnStart()
{
    this.Start = DateTime.Now;
}

public void OnEnd()
{
    this.End = DateTime.Now;
}

public TimeSpan GetDuration()
{
    return this.End - this.Start;
}
Enter fullscreen mode Exit fullscreen mode

The timespan is able to hold the difference between two datetimes despite the format, which is really cool.

Top comments (2)

Collapse
 
bambutz profile image
BamButz

Hey Brandon, could you elaborate why you think this is a better solution? Is it because it seems to be more simple?

Collapse
 
brandonmweaver profile image
Brandon Weaver

I should have mentioned that I needed to know the start date and time, and so it was an especially convenient solution for my particular problem. There are certainly other simple/efficient approaches.