Converting the date time to display milliseconds in C#(在 C# 中将日期时间转换为显示毫秒)
问题描述
我想显示毫秒,但 ToString 显示毫秒为 00000.
I want to show the milliseconds, but ToString shows the milliseconds as 00000.
我提供下面的代码,以及每一步的输出.
I am providing the code below, with the output at each step.
String currentDateTime = DateTime.Now.ToString("G");
输出 - 2011 年 7 月 27 日下午 3:05:31
Output - 7/27/2011 3:05:31 PM
System.DateTime dateTime = System.DateTime.Parse(currentDateTime);
输出 - 2011 年 7 月 27 日下午 3:05:31
Output - 7/27/2011 3:05:31 PM
String dateTimeStr = dateTime.ToString("hh.mm.ss.ffffff", "en-US");
输出 - 03.05.32.000000
Output - 03.05.32.000000
我想用毫秒显示输出,例如 03.05.32.33456
I want to show the output with the milliseconds , eg 03.05.32.33456
如果我使用 ParseExact 而不是 Parse,我会遇到异常.我知道我可以使用 TryParseExact,但那个解决方案可能不合适,因为我需要一个通用的解决方案来解决这个问题.
If I used ParseExact instead of Parse, I am getting an exception. I know that I can use TryParseExact, but that solution might not be suitable , as I need a generic solution to this problem .
谁能帮帮我.
提前致谢.苏杰
推荐答案
通过使用之前从字符串构建的相同 dateTime 对象(7/27/2011 3:05:31 PM"没有任何毫秒),您'正在失去毫秒.
By using the same dateTime object that you previously built from a string ("7/27/2011 3:05:31 PM" without any milliseconds), you're losing the milliseconds.
如果您直接将 Now 转换为字符串,则不会丢失毫秒数:
If you were to convert Now to a string directly, you would not lose the milliseconds:
String dateTimeStr = DateTime.Now.ToString("hh.mm.ss.ffffff", "en-US");
这篇关于在 C# 中将日期时间转换为显示毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中将日期时间转换为显示毫秒
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
