[英]Elegant way to convert yyyyyMMddHHmmssffff string into acceptable value for DateTime.Parse?
I have "202006260718083370" as an input value and I need to convert it into parse -able string for DateTime.Parse.我有“202006260718083370”作为输入值,我需要将其转换成DateTime.Parse解析-able字符串。 Any elegant way that you can think of aside from the approach below?
除了下面的方法,你还能想到什么优雅的方法?
Approach 1 - Individually insert string in between.方法 1 - 在中间单独插入字符串。
var input = "202006260718083370".Insert(5, "-")
.Insert(8, "-")
.Insert(11, " ")
.Insert(14, ":")
.Insert(17, ":")
.Insert(20, ".");
var dateTime = DateTime.Parse("2020-06-26 07:18:08.3370") // What input looks like
Approach 2 - individually pass in new DateTime(....)方法 2 - 单独传入 new DateTime(....)
var year = "202006260718083370".Substring(0, 4);
var month = "202006260718083370".Substring(4, 2);
var date = "202006260718083370".Substring(6, 2);
var hour = "202006260718083370".Substring(8, 2);
var min = "202006260718083370".Substring(10, 2);
var sec = "202006260718083370".Substring(12, 2);
var mil = "202006260718083370".Substring(14, 4);
Approach 3 - almost the same in approach 2. Use string array and concat.方法 3 - 与方法 2 几乎相同。使用字符串数组和连接。 Like the answer here .
喜欢这里的答案。
Use DateTime.ParseExact with your format将DateTime.ParseExact与您的格式一起使用
From documentation:从文档:
Converts the specified string representation of a date and time to its DateTime equivalent.
将日期和时间的指定字符串表示形式转换为其等效的 DateTime。 The format of the string representation must match a specified format exactly or an exception is thrown.
字符串表示的格式必须与指定的格式完全匹配,否则会引发异常。
var provider = CultureInfo.InvariantCulture;
var parsedDateTime = DateTime.ParseExact("202006260718083370", "yyyyMMddHHmmssffff", provider);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.