如何将秒转换为(小时:分钟:秒:毫秒)时间?

假设我有80秒;. net中有没有专门的类/技术可以让我把这80秒转换成(00h:00m:00s:00ms)格式,比如convert。ToDateTime之类的?


当前回答

private string ConvertTime(double miliSeconds)
{
    var timeSpan = TimeSpan.FromMilliseconds(totalMiliSeconds);
    // Converts the total miliseconds to the human readable time format
    return timeSpan.ToString(@"hh\:mm\:ss\:fff");
}

/ /测试

    [TestCase(1002, "00:00:01:002")]
    [TestCase(700011, "00:11:40:011")]
    [TestCase(113879834, "07:37:59:834")]
    public void ConvertTime_ResturnsCorrectString(double totalMiliSeconds, string expectedMessage)
    {
        // Arrange
        var obj = new Class();;

        // Act
        var resultMessage = obj.ConvertTime(totalMiliSeconds);

        // Assert
        Assert.AreEqual(expectedMessage, resultMessage);
    }

其他回答

我建议您为此使用TimeSpan类。

public static void Main(string[] args)
{
    TimeSpan t = TimeSpan.FromSeconds(80);
    Console.WriteLine(t.ToString());

    t = TimeSpan.FromSeconds(868693412);
    Console.WriteLine(t.ToString());
}

输出:

00:01:20
10054.07:43:32

这将以hh:mm:ss格式返回

 public static string ConvertTime(long secs)
    {
        TimeSpan ts = TimeSpan.FromSeconds(secs);
        string displayTime = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}";
        return displayTime;
    }

在VB。NET,但是在c#中也是一样的:

Dim x As New TimeSpan(0, 0, 80)
debug.print(x.ToString())
' Will print 00:01:20

对于。net < 4.0 (e.x: Unity),你可以写一个扩展方法来拥有TimeSpan。ToString(字符串格式)行为,如。net > 4.0

public static class TimeSpanExtensions
{
    public static string ToString(this TimeSpan time, string format)
    {
        DateTime dateTime = DateTime.Today.Add(time);
        return dateTime.ToString(format);
    }
}

在你的代码中,你可以像这样使用它:

var time = TimeSpan.FromSeconds(timeElapsed);

string formattedDate = time.ToString("hh:mm:ss:fff");

通过这种方式,您可以简单地从代码的任何地方调用ToString来格式化任何TimeSpanobject。

如果您知道您有一个秒数,您可以通过调用TimeSpan来创建一个TimeSpan值。FromSeconds:

 TimeSpan ts = TimeSpan.FromSeconds(80);

您可以获取天、小时、分钟或秒的数量。或者使用一个ToString重载以任何您喜欢的方式输出它。