Running Rabbit
Running Rabbit

Reputation: 2720

Not able to convert a string value to Date time including milliseconds

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

Answers (3)

Tetsuya Yamamoto
Tetsuya Yamamoto

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

DLL_Whisperer
DLL_Whisperer

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);

enter image description here

Upvotes: 0

Dhaval Pankhaniya
Dhaval Pankhaniya

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

Related Questions