简体   繁体   中英

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. Any elegant way that you can think of aside from the approach below?

Approach 1 - Individually insert string in between.

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(....)

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. Like the answer here .

Use DateTime.ParseExact with your format

From documentation:

Converts the specified string representation of a date and time to its DateTime equivalent. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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