时间跨度字符串格式

本文关键字:格式 字符串 时间跨度 | 更新日期: 2023-09-27 17:56:43

>我有一个时间跨度,我需要以特定的格式输出,如下所示:-

TimeSpan TimeDifference = DateTime.Now - RandomDate;

我正在像这样格式化时间跨度:-

string result = string.Format(@"{0:hh':mm':ss}", TimeDifference);

结果将如下所示:-

"00:16:45.6184635"

如何将这些秒四舍五入到小数点后 0 位?

Expected Result = 00:16:46

谢谢

时间跨度字符串格式

你的代码适用于 .NET 4,但不适用于 3.5,因为 4 上发生了重大更改,TimeSpan现在实现了IFormattable(见下文)。

在 3.5 或更低版本上,您可以做的是将TimeSpan转换为 DateTime 并使用 ToString

DateTime dtime = DateTime.MinValue.Add(TimeDifference);
string result = dtime.ToString(@"hh':mm':ss");

这里你可以看到非工作+工作版本:http://ideone.com/Ak1HuD


编辑我认为它有时有效而有时无效的原因是,因为 .NET 4.0 TimeSpan实现了似乎被String.Format使用的IFormattable

您的代码应该可以正常工作(在删除小语法错误之后)。请考虑以下示例:

TimeSpan TimeDifference = DateTime.Now - DateTime.Now.AddHours(-6);
string result = string.Format(@"{0:hh':mm':ss}", TimeDifference);
Console.WriteLine("TimeSpan: {0}", TimeDifference.ToString());
Console.WriteLine("Formatted TimeSpan: {0}", result);

输出:

TimeSpan: 05:59:59.9990235
Formatted TimeSpan: 05:59:59
对我来说

效果很好。

例如,此程序:

using System;
namespace Demo
{
    public static class Program
    {
        private static void Main(string[] args)
        {
            DateTime then = new DateTime(2013, 1, 30, 0, 1, 3);
            TimeSpan ts = DateTime.Now - then;
            Console.WriteLine(ts.ToString());
            Console.WriteLine(ts.ToString(@"hh':mm':ss"));
            Console.WriteLine(string.Format(@"{0:hh':mm':ss}", ts));
            // Or, with rounding:
            TimeSpan rounded = TimeSpan.FromSeconds((int)(0.5 + ts.TotalSeconds));
            Console.WriteLine(rounded.ToString(@"hh':mm':ss"));
        }
    }
}

输出如下内容:

1.09:20:22.5070754
09:20:22
09:20:22
09:20:23 <- Note rounded up to :23