Convert TimeSpan.TotalMilliseconds to datetime and

2019-08-17 09:24发布

问题:

I kinda confuse about the date time conversion

in my model i have defined

    public DateTime? Sent { get; set; }
    public DateTime? Reply { get; set; }
    public double ResponseTime { get; set; }

in linq part i am using

ResponseTime = (u.Reply - u.sent).TotalMilliseconds

which is not formated and displayed like this 979809803

I want to know how do i convert it to datetime format, and eventually will display the format as hour:minute, for instance 2:45 between the date sent and date reply.

回答1:

Subtracting a DateTime from a DateTime yields a TimeSpan. Have a look at the TimeSpan.ToString Method (String) to see how you can custom format the value.

You can change ResponseTime back to a TimeSpan and from there to a string.

TimeSpan ResponseTimeSpan = new TimeSpan(0, 0, 0, (int)ResponseTime);

string ResponseTimeDisplay = ResponseTimeSpan.ToString();


回答2:

Just return the TimeSpan and call .ToString("hh:mm").

TimeSpan.ToString

public TimeSpan ResponseTime { get; set; }

//usage in LINQ
ResponseTime = (u.Reply - u.Sent)

When displaying...

value.ResponseTime.ToString("hh:mm")