C# 如何在 .NET 中使用自定义格式对 TimeSpan 对象进行 String.Format 格式化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/574881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I String.Format a TimeSpan object with a custom format in .NET?
提问by Hosam Aly
What is the recommended way of formatting TimeSpan
objects into a string with a custom format?
TimeSpan
使用自定义格式将对象格式化为字符串的推荐方法是什么?
采纳答案by Doctor Jones
Please note: this answer is for .Net 4.0 and above. If you want to format a TimeSpan in .Net 3.5 or below please see JohannesH's answer.
请注意:此答案适用于 .Net 4.0 及更高版本。如果您想在 .Net 3.5 或更低版本中格式化 TimeSpan,请参阅JohannesH 的回答。
Custom TimeSpan format strings were introduced in .Net 4.0. You can find a full reference of available format specifiers at the MSDN Custom TimeSpan Format Stringspage.
.Net 4.0 中引入了自定义 TimeSpan 格式字符串。您可以在 MSDN自定义时间跨度格式字符串页面上找到可用格式说明符的完整参考。
Here's an example timespan format string:
这是一个示例时间跨度格式字符串:
string.Format("{0:hh\:mm\:ss}", myTimeSpan); //example output 15:36:15
(UPDATE) and here is an example using C# 6 string interpolation:
( UPDATE) 这里是一个使用 C# 6 字符串插值的例子:
$"{myTimeSpan:hh\:mm\:ss}"; //example output 15:36:15
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 Stringspage explains about escaping the ":" and "." characters in a format string:
这段摘自 MSDN自定义时间跨度格式字符串页面解释了如何转义“:”和“.”。格式字符串中的字符:
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.
自定义 TimeSpan 格式说明符不包括占位符分隔符,例如将天与小时、小时与分钟或秒与小数秒分开的符号。相反,这些符号必须作为字符串文字包含在自定义格式字符串中。例如,“dd.hh:mm”将句点 (.) 定义为天和小时之间的分隔符,将冒号 (:) 定义为小时和分钟之间的分隔符。
回答by Hosam Aly
One way is to create a DateTime
object and use it for formatting:
一种方法是创建一个DateTime
对象并将其用于格式化:
new DateTime(myTimeSpan.Ticks).ToString(myCustomFormat)
// or using String.Format:
String.Format("{0:HHmmss}", new DateTime(myTimeSpan.Ticks))
This is the way I know. I hope someone can suggest a better way.
这是我所知道的方式。我希望有人可以提出更好的方法。
回答by JohannesH
For .NET 3.5 and lower you could use:
对于 .NET 3.5 及更低版本,您可以使用:
string.Format ("{0:00}:{1:00}:{2:00}",
(int)myTimeSpan.TotalHours,
myTimeSpan.Minutes,
myTimeSpan.Seconds);
Code taken from a Jon Skeet answeron bytes
代码取自 Jon Skeet对字节的回答
For .NET 4.0 and above, see DoctaJonez answer.
对于 .NET 4.0 及更高版本,请参阅 DoctaJonez回答。
回答by Harpal
This is awesome one:
这是一个很棒的:
string.Format("{0:00}:{1:00}:{2:00}",
(int)myTimeSpan.TotalHours,
myTimeSpan.Minutes,
myTimeSpan.Seconds);
回答by KKK
回答by Enel Almonte
Dim duration As New TimeSpan(1, 12, 23, 62)
DEBUG.WriteLine("Time of Travel: " + duration.ToString("dd\.hh\:mm\:ss"))
It works for Framework 4
它适用于框架 4
回答by NeverHopeless
You can also go with:
你也可以去:
Dim ts As New TimeSpan(35, 21, 59, 59) '(11, 22, 30, 30) '
Dim TimeStr1 As String = String.Format("{0:c}", ts)
Dim TimeStr2 As String = New Date(ts.Ticks).ToString("dd.HH:mm:ss")
EDIT:
编辑:
You can also look at Strings.Format.
您还可以查看Strings.Format。
Dim ts As New TimeSpan(23, 30, 59)
Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")
回答by NoOne
Personally, I like this approach:
就个人而言,我喜欢这种方法:
TimeSpan ts = ...;
string.Format("{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ts);
You can make this as custom as you like with no problems:
您可以随心所欲地进行自定义,没有任何问题:
string.Format("{0:%d}days {0:%h}hours {0:%m}min {0:%s}sec", ts);
string.Format("{0:%d}d {0:%h}h {0:%m}' {0:%s}''", ts);
回答by panpawel
I used the code below. It is long, but still it is one expression, and produces very friendly output, as it does not outputs days, hours, minutes, or seconds if they have value of zero.
我使用了下面的代码。它很长,但仍然是一个表达式,并且产生非常友好的输出,因为如果它们的值为零,它不会输出天、小时、分钟或秒。
In the sample it produces output: "4 days 1 hour 3 seconds".
在示例中,它产生输出:“4 天 1 小时 3 秒”。
TimeSpan sp = new TimeSpan(4,1,0,3);
string.Format("{0}{1}{2}{3}",
sp.Days > 0 ? ( sp.Days > 1 ? sp.ToString(@"d\ \d\a\y\s\ "): sp.ToString(@"d\ \d\a\y\ ")):string.Empty,
sp.Hours > 0 ? (sp.Hours > 1 ? sp.ToString(@"h\ \h\o\u\r\s\ ") : sp.ToString(@"h\ \h\o\u\r\ ")):string.Empty,
sp.Minutes > 0 ? (sp.Minutes > 1 ? sp.ToString(@"m\ \m\i\n\u\t\e\s\ ") :sp.ToString(@"m\ \m\i\n\u\t\e\ ")):string.Empty,
sp.Seconds > 0 ? (sp.Seconds > 1 ? sp.ToString(@"s\ \s\e\c\o\n\d\s"): sp.ToString(@"s\ \s\e\c\o\n\d\s")):string.Empty);
回答by Niko
I use this method. I'm Belgian and speak dutch so plural of hours and minutes is not just adding 's' to the end but almost a different word than singular.
我用这个方法。我是比利时人,会说荷兰语,因此小时和分钟的复数不仅仅是在末尾添加“s”,而且几乎是与单数不同的词。
It may seem long but it is very readable I think:
它可能看起来很长,但我认为它非常易读:
public static string SpanToReadableTime(TimeSpan span)
{
string[] values = new string[4]; //4 slots: days, hours, minutes, seconds
StringBuilder readableTime = new StringBuilder();
if (span.Days > 0)
{
if (span.Days == 1)
values[0] = span.Days.ToString() + " dag"; //day
else
values[0] = span.Days.ToString() + " dagen"; //days
readableTime.Append(values[0]);
readableTime.Append(", ");
}
else
values[0] = String.Empty;
if (span.Hours > 0)
{
if (span.Hours == 1)
values[1] = span.Hours.ToString() + " uur"; //hour
else
values[1] = span.Hours.ToString() + " uren"; //hours
readableTime.Append(values[1]);
readableTime.Append(", ");
}
else
values[1] = string.Empty;
if (span.Minutes > 0)
{
if (span.Minutes == 1)
values[2] = span.Minutes.ToString() + " minuut"; //minute
else
values[2] = span.Minutes.ToString() + " minuten"; //minutes
readableTime.Append(values[2]);
readableTime.Append(", ");
}
else
values[2] = string.Empty;
if (span.Seconds > 0)
{
if (span.Seconds == 1)
values[3] = span.Seconds.ToString() + " seconde"; //second
else
values[3] = span.Seconds.ToString() + " seconden"; //seconds
readableTime.Append(values[3]);
}
else
values[3] = string.Empty;
return readableTime.ToString();
}//end SpanToReadableTime