pcbabu pcbabu - 4 months ago 18
C# Question

How to find exact format of a date string?

I need to know exact date format that will perse the string

16-Aug-78 12:00:00 AM
. I have tried various string like "ss-MMM-yy hh:mm:ss". Is there any way for finding it to converting to any general format. I am using
CultureInfo.InvariantCulture
class.

Answer

Your string format is wrong. It has to match your string format exactly. You can use dd-MMM-yy hh:mm:ss tt format instead.

Here an example in LINQPad.

string s = "16-Aug-78 12:00:00 AM";
var date = DateTime.ParseExact(s, "dd-MMM-yy hh:mm:ss tt",
                               CultureInfo.InvariantCulture);
date.Dump();

Or, since dd-MMM-yy hh:mm:ss tt is a standart date and time format for InvariantCulture, you can directly DateTime.Parse method like;

string s = "16-Aug-78 12:00:00 AM";
var date = DateTime.Parse(s, CultureInfo.InvariantCulture);
date.Dump();

Here a demonstration.

Is there any way for finding it to converting to any general format?

There is no way to get format of a string except you create your own formatting. Only you can know what is your string format exactly, computer can't.

For example; 01/02/2014 can be 1 February 2014 or 2 January 2014 depends on which custom format you can parse it.