Jür*_*ock 17 c# string.format timespan
我想在字符串中显示两个日期之间的经过时间.
假设我有以下代码:
DateTime date1 = DateTime.Now();
System.Threading.Thread.Sleep(2500);
DateTime date2 = DateTime.Now();
TimeSpan elapsed = date2.substract(date1);
Console.WriteLine("> {0:hh:mm:ss}", elapsed);
Run Code Online (Sandbox Code Playgroud)
我期待的是:
> 00:00:03
Run Code Online (Sandbox Code Playgroud)
我得到了什么:
> 00:00:02.5002500
Run Code Online (Sandbox Code Playgroud)
有没有办法使用String.Format函数只返回完整秒?
我还尝试删除小数位:
elapsed = elapsed.Substract(TimeSpan.FromMiliseconds((double)Timespan.Miliseconds);
Run Code Online (Sandbox Code Playgroud)
但是,自从elapsed以来,这都不起作用.Miliseconds返回500作为整数.
Rei*_*ica 22
Change the
Console.WriteLine("> {0:hh:mm:ss}", elapsed);
Run Code Online (Sandbox Code Playgroud)
to
Console.WriteLine("> {0:hh\\:mm\\:ss}", elapsed);
Run Code Online (Sandbox Code Playgroud)
.Net 4 allows you to use custom format strings with Timespan. You can find a full reference of available format specifiers at the MSDN Custom TimeSpan Format Strings page.
You need to escape the ":" character with a "\" (which itself must be escaped unless you're using a verbatim string).
This excerpt from the MSDN Custom TimeSpan Format Strings page explains about escaping the ":" and "." characters in a format string:
The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.
Mar*_*len 13
不幸的是,不可能以TimeSpan与DateTime值相同的方式格式化a .但是,您可以进行快速转换,因为TimeSpan和DateTime都将其值存储为刻度(在Ticks属性中).
在你的代码中看起来像这样:
Console.WriteLine("> {0:hh:mm:ss}", new DateTime(elapsed.Ticks));Run Code Online (Sandbox Code Playgroud)
更新:这适用于.NET 3.5及更早版本,.NET 4支持格式化TimeSpans.
该类TimeSpan具有Hours、Minutes和Seconds属性,它们分别返回每个时间部分。所以你可以尝试:
String.Format(CultureInfo.CurrentCulture, "{0}:{1}:{2}",
elapsed.Hours,
elapsed.Minutes,
elapsed.Seconds)
Run Code Online (Sandbox Code Playgroud)
以获得您想要的格式。
可能有更优化的方法,但我还没有找到。
Timespan duration = endDateTime - startDateTime;
duration.ToString("hh\\:mm\\:ss");
Run Code Online (Sandbox Code Playgroud)