Michael
Michael

Reputation: 251

How to reformat a date within a text file C#

I'm taking in an error log cleaning it and then outputting it and putting the text file into machine learning, for this the date within the text file needs to be in the following format: "yyyy-MM-dd HH:mm:ss", currently the date is in the following: Wed Oct 29 13:36:08 2014.

I had something similar for formatting date in an access log however with the year coming after the time this is making it difficult for me to format, can anyone suggest anything that would work?

cleanArray[3] holds the date and time in the format: Wed Oct 29 14:01:02 2014. You can see i've commented out trying to reformat it, but i'm stumped with where the year comes. Thanks in advance!!

Upvotes: 1

Views: 67

Answers (2)

mateuszlewko
mateuszlewko

Reputation: 1129

So you almost got it correct. Try this code for parsing into desired format:

var date = DateTime.ParseExact("Wed Oct 29 14:01:02 2014", "ddd MMM dd HH:mm:ss yyyy",  CultureInfo.InvariantCulture);
var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(newDateString);

You forgot about dd part in your format string.

Upvotes: 1

Equalsk
Equalsk

Reputation: 8194

You code is fine, you have just missed dd out of your format for ParseExact. As the name suggests, the format must be exact.

// Get date string e.g. 'Wed Oct 29 14:01:02 2014'
var dateString = cleanArray[3];

// See the 'dd' for the day
var date = DateTime.ParseExact(dateString, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture); 

// Output to desired format
var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");

// Replace value in array
cleanArray[3] = newDateString;

Upvotes: 1

Related Questions