C# Display Milliseconds in hh:mm:ss format

时间:2015-09-01 22:18:30

标签: c# datetime

I am trying to write a program that has the function to lock the computer after a specified amount of time once the program is activated. The problem im having is getting the time remaining to display properly. I am trying to do this using datetime vs a switch/if scenario. display a countdown timer based on a user specified about of time. More specifically what I want to do is

1) the user specifies amount of minutes 2) the minutes is programmatically converted to milliseconds 3 where im stuck) Milliseconds is converted and displayed via label in hh:mm:ss.

I have spent a couple days searching and I don't quite understand the MSDN examples and I haven't been able to come a cross the way to do this. Found plenty of examples for going from datetime to milliseconds though.

1 个答案:

答案 0 :(得分:9)

TimeSpan would be better suited since you're talking about a duration, not a point in time. You can create a TimeSpan from milliseconds and then format it with ToString():

int ms = 123456;
TimeSpan ts = TimeSpan.FromMilliseconds(ms);
Console.WriteLine(ts.ToString(@"hh\:mm\:ss"));