Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove Milliseconds from the TimeSpan in C#? [duplicate]

Tags:

c#

I am new to c# and using windows forms. the result of this code is: 01:38:07.0093844 . Anyone knows how can I remove the millisecond part (0093844) from the result (ts) I want the result to look like this : 01:38:07 (H:mm:ss) without millisecond .

Please help .Thank you

string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;

TimeSpan  ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime)); //Difference

//result of ts = 01:38:07.0093844
like image 330
Kate Avatar asked Mar 02 '16 14:03

Kate


1 Answers

Create an extension method:

public static class TimeExtensions
{
    public static TimeSpan StripMilliseconds(this TimeSpan time)
    {
        return new TimeSpan(time.Days, time.Hours, time.Minutes, time.Seconds);
    }
}

Usage:

string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;

TimeSpan  ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime)).StripMilliseconds();

To format (make into a string) without milliseconds use this:

string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;

TimeSpan  ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime));
string formatted = ts.ToString(@"dd\.hh\:mm\:ss");
like image 183
Tom Avatar answered Sep 22 '22 11:09

Tom