











一直在用DateTime, 却不常用TimeSpan , 今天突然用到了, 发现不知道咋做格式化...百度一下,找到了答案, 在这记录一下, 免得以后找花费时间
以下内容摘抄自 Microsoft Docs 原文地址: https://docs.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/ee372287(v=vs.95)
分别展示了ToString方法跟string.Format方法中的方法, 其中string.Format的用法可以在mvc的Html.TextBox的format参数中使用
这里只记录下基本用法, 更多使用参考请移步上方链接.
TimeSpan转字符串
using System; public class Example { public static void Demo(System.Windows.Controls.TextBlock outputBlock) { TimeSpan duration = new TimeSpan(1, 12, 23, 62); string output = null; output = "Time of Travel: " + duration.ToString("%d") + " days"; outputBlock.Text += output + Environment.NewLine; output = "Time of Travel: " + duration.ToString(@"dd\.hh\:mm\:ss"); outputBlock.Text += output + Environment.NewLine; outputBlock.Text += String.Format("Time of Travel: {0:%d} day(s)", duration) + Environment.NewLine; outputBlock.Text += String.Format("Time of Travel: {0:dd\\.hh\\:mm\\:ss} days", duration) + Environment.NewLine; } } // The example displays the following output: // Time of Travel: 1 days // Time of Travel: 01.12:24:02 // Time of Travel: 1 day(s) // Time of Travel: 01.12:24:02 days
字符串转TimeSpan
using System; public class Example { public static void Demo(System.Windows.Controls.TextBlock outputBlock) { string value = null; TimeSpan interval; value = "6"; if (TimeSpan.TryParseExact(value, "%d", null, out interval)) outputBlock.Text += String.Format("{0} --> {1}", value, interval.ToString("c")) + Environment.NewLine; else outputBlock.Text += String.Format("Unable to parse '{0}'", value) + Environment.NewLine; value = "16:32.05"; if (TimeSpan.TryParseExact(value, @"mm\:ss\.ff", null, out interval)) outputBlock.Text += String.Format("{0} --> {1}", value, interval.ToString("c")) + Environment.NewLine; else outputBlock.Text += String.Format("Unable to parse '{0}'", value) + Environment.NewLine; value= "12.035"; if (TimeSpan.TryParseExact(value, "ss\\.fff", null, out interval)) outputBlock.Text += String.Format("{0} --> {1}", value, interval.ToString("c")) + Environment.NewLine; else outputBlock.Text += String.Format("Unable to parse '{0}'", value) + Environment.NewLine; } } // The example displays the following output: // 6 --> 6.00:00:00 // 16:32.05 --> 00:16:32.0500000 // 12.035 --> 00:00:12.0350000
参数表格
The following table describes the custom date and time format specifiers.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。