将字符串转换为DateTime且具有超过7个十进制的毫秒 [英] Converting a string to a DateTime with more than 7 decimals of milliseconds

查看:68
本文介绍了将字符串转换为DateTime且具有超过7个十进制的毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试将以下格式的字符串日期转换为DateTime。当使用格式字符串 fffffff以秒为单位的7位小数时,我可以使用ParseExact解析它,但是我得到的字符串可以(并非总是)有9位小数的秒。

So I am trying to convert a string date in the following format to a DateTime. I am able to parse it using ParseExact when there are 7 decimals of fractions of a second using the format string "fffffff", but the string I'm getting can (doesn't always) have 9 decimals of fractions of a second.

我并不在乎最后几位数字,因为无论如何我都会四舍五入。我正在寻找某种方法来解析它们或截断它们,然后再从ParseExact方法得到错误,因为它与 fffffff不匹配。我唯一的想法是根据小数点后的字符数截断字符串。有没有更简单的方法可以做到这一点?

I don't really care what those last few digits are as I'm going to end up rounding it anyways. What I'm looking for is some way to either parse them or truncate them before I get an error from the ParseExact method because it doesn't match up with "fffffff". My only thought would be to truncate the string based on the number of characters after the decimal point. Is there an easier way to do this? Thanks in advance!

要解析的示例字符串: 2015-12-10 13:14:15.123456789

Sample string to parse: "2015-12-10 13:14:15.123456789"

DateTime.ParseExact("2015-12-10 13:14:15.123456789", "yyyy-MM-dd HH:mm:ss.fffffff", System.Globalization.CultureInfo.InvariantCulture);

抛出FormatException,但以下工作有效。

throws a FormatException, but the following works.

DateTime.ParseExact("2015-12-10 13:14:15.1234567", "yyyy-MM-dd HH:mm:ss.fffffff", System.Globalization.CultureInfo.InvariantCulture);


推荐答案

我不相信您可以使用常规解析代码和现有文本。 DateTime 的精度仅下降到刻度,即刻度为100纳秒。我认为最简单的方法是截断字符串本身:

I don't believe you can do this with the normal parsing code and the existing text. DateTime's precision only goes down to ticks, where a tick is 100 nanoseconds. I think the simplest thing to do is truncate the string itself:

string pattern = "yyyy-MM-dd HH:mm:ss.fffffff";
if (text.Length > pattern.Length)
{
    text = text.Substring(0, pattern.Length);
}
DateTime value = DateTime.ParseExact(text, pattern, CultureInfo.InvariantCulture);

强制性插件: Noda Time 2.0,您不需要这样做,因为它支持纳秒级的精度:)

Obligatory plug: in Noda Time 2.0 you won't need to do this as it supports a precision of nanoseconds :)

这篇关于将字符串转换为DateTime且具有超过7个十进制的毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆