C# 如何将 TimeSpan 转换为 24 小时和分钟字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18482460/
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 convert TimeSpan to 24 hours and minutes String?
提问by Majid
I use this code for converting Timespan
to String
(for ex: 14:53) :
我使用此代码转换Timespan
为String
(例如:14:53):
myTimeSpan.ToString("hh:mm");
but this error occurs:
但发生此错误:
Input string was not in a correct format
输入字符串的格式不正确
What is the proper way to do this?
这样做的正确方法是什么?
采纳答案by Tim Schmelter
myTimeSpan.ToString(@"hh\:mm")
Custom TimeSpan Format Strings
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 Bassam Alugili
Try this will work 100% !!
试试这将 100% 工作!!
myTimeSpan.ToString(@"dd\.hh\:mm");.
回答by Soner G?nül
From TimeSpan.ToString Method (String)
从 TimeSpan.ToString Method (String)
TimeSpan t = new TimeSpan(14, 53, 0);
Console.WriteLine(t.ToString(@"hh\:mm"));
As an alternative you can use String.Format
like;
作为替代,您可以使用String.Format
like;
Console.WriteLine(String.Format("{0}:{1}", t.Hours, t.Minutes));
Remember, TimeSpan.ToString(String)
overload only avaiable for .NET 4 or higher.
请记住,TimeSpan.ToString(String)
重载仅适用于 .NET 4 或更高版本。
回答by Sriram Sakthivel
回答by Damith
var result = string.Format("{0:D2}:{1:D2}", myTimeSpan.Hours, myTimeSpan.Minutes);