简体   繁体   English

为什么C#DateTime字符串格式不起作用?

[英]Why doesn't C# DateTime string formatting work?

The following code doesn't format the time properly. 以下代码无法正确格式化时间。 All I want is minutes:seconds:milliseconds_with_3_decimals but no matter what formatting I choose it gets ignored and the time is displayed with default formatting. 我想要的只是minutes:seconds:milliseconds_with_3_decimals,但是无论我选择哪种格式,它都将被忽略,并以默认格式显示时间。

Log(LogMsgType.Normal, String.Format("+{0:mm:ss.fff} ", DateTime.Now.Subtract(latest)));

代码输出

You need to look into formatting of TimeSpan , not DateTime . 您需要研究TimeSpan格式,而不是DateTime格式。 This was new in .NET 4.0 (Visual Studio 2010). 这是.NET 4.0(Visual Studio 2010)中的新增功能。 See: MSDN: Custom TimeSpan Format Strings . 请参阅: MSDN:自定义TimeSpan格式字符串

I would try something like: 我会尝试类似的东西:

String.Format("+{0:mm':'ss'.'fff} ", DateTime.Now - latest)

(Better check first that it's never over 60 minutes, otherwise you will lose the most significant part of the time span.) (最好先检查一下它不会超过60分钟,否则您将失去时间段中最重要的部分。)

NOTE: If you're on .NET 3.5 or earlier, this won't work as TimeSpan wasn't IFormattable in those versions. 注意:如果您使用的是.NET 3.5或更早版本,则由于这些版本中的TimeSpan并非IFormattable ,因此无法IFormattable In that case I recommend: 在这种情况下,我建议:

var span = DateTime.Now - latest;
  ...
String.Format("+{0:D2}:{1:D2}.{2:D3} ", span.Minutes, span.Seconds, span.Milliseconds)

You want: 你要:

@"+{0:mm\:ss\.fff} "

You have to escape the colon and period 你必须逃避结肠和月经

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM