Reputation: 2720
I have a string value which I need to convert to DateTime
currentDate="29-APR-17 03.42.06.410000 PM"
I tried the below statement, but its throwing error:
DateTime originalDate = DateTime.Parse(currentDate);
DateTime originalDate = Convert.ToDateTime(currentDate);
I even followed this link "https://msdn.microsoft.com/en-us/library/bb882581(v=vs.110).aspx" but is is also not helping
Moreover, the information provided in Stackoverflow was not helping as I am always facing the error String was not recognized as a valid DateTime.
Upvotes: 1
Views: 689
Reputation: 24957
The DateTime.ParseExact
should solve the formatting like this:
DateTime originalDate = DateTime.ParseExact(currentDate, "dd-MMM-yy hh.mm.ss.ffffff tt", CultureInfo.InvariantCulture, DateTimeStyles.None);
or if time part are separated with colons:
DateTime.ParseExact(currentDateWithColons, "dd-MMM-yy hh:mm:ss.ffffff tt", CultureInfo.InvariantCulture, DateTimeStyles.None);
Both dots and colons producing the same result using Console.WriteLine(originalDate.ToString("dd/MM/yyyy hh:mm:ss.ffffff tt"))
:
29/04/2017 03:42:06.410000 PM
Working example: .NET Fiddle Demo
Upvotes: 3
Reputation: 837
string currentDate = "29-APR-17 03:42:06.410000 PM";
var date = DateTime.ParseExact(currentDate, "dd-MMM-yy hh:mm:ss.ffffff tt", CultureInfo.InvariantCulture);
Upvotes: 0
Reputation: 1996
try below code
string currentDate="29-APR-17 03:42:06.410000 PM"
DateTime originalDate = DateTime.Parse(currentDate);
originalDate = Convert.ToDateTime(currentDate);
Console.WriteLine(originalDate.ToString("dd-MM-yyyy-fff"));
you were using wrong format use : instead of . in time.
changed "29-APR-17 03.42.06.410000 PM" to "29-APR-17 03:42:06.410000 PM"
Upvotes: 0