Click here to Skip to main content
15,671,383 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:

I have a string like below which is I am converting to datetime format. I tried in below way. Is there any other way to do it. Expected outcome of string after formatting should be like yyyy-MM-dd hh:mm:ss ms.

What I have tried:

StringBuilder myStringBuilder = new StringBuilder("20180215031530000");
myStringBuilder = myStringBuilder.Insert(4, "-");
myStringBuilder = myStringBuilder.Insert(7, "-");
myStringBuilder = myStringBuilder.Insert(10, " ");
myStringBuilder = myStringBuilder.Insert(13, ":");
myStringBuilder = myStringBuilder.Insert(16, ":");
myStringBuilder = myStringBuilder.Insert(19, ".");
DateTime dt = Convert.ToDateTime(myStringBuilder.ToString());
Updated 15-Feb-19 0:32am

Share this answer
In addition to solution 1 a concrete example:
var originalTimeString = "20180215031530000";

DateTime dt;

var success = DateTime.TryParseExact(originalTimeString, "yyyyMMddhhmmssfff", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

if (success)
    var newTimeString = dt.ToString("yyyy-MM-dd hh:mm:ss fff");

Nevertheless please read the suggested documentation.
Share this answer
Don't do that.
Use DateTime.TryParseExact[^] instead of inserting delimiters:
string input = "20180215031530000";
DateTime dt;
if (!DateTime.TryParseExact(input, "yyyyMMddHHmmssfff", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    Console.WriteLine("Problem with input date");
Share this answer
Richard MacCutchan 15-Feb-19 5:08am    
Dang, I missed that, must scroll further.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900