Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Try as below

var dstring = "16-Aug-78 12:00:00 AM";
DateTime result;
var matchingCulture = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(ci => DateTime.TryParse(dstring, ci, DateTimeStyles.None, out result))

You have wrong format string, you are using ss for day it should be dd. This article Custom Date and Time Format Strings explains what you need for custom format.

Use

"dd-MMM-yy hh:mm:ss tt"

Instead of

"ss-MMM-yy hh:mm:ss"

You can use DateTime.ParseExact to parse the string.

DateTime dt = DateTime.ParseExact("16-Aug-78 12:00:00 AM", "dd-MMM-yy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None);

You can try with DateTime.TryParseExact():

string strDate = "16-Aug-78 12:00:00 AM";           
DateTime datDate;
if(DateTime.TryParseExact(strDate , new string[] {"dd-MMM-yy hh:mm:ss tt" },
                       System.Globalization.CultureInfo.InvariantCulture,
                       System.Globalization.DateTimeStyles.None, out datDate))
 {
   Console.WriteLine(datDate);
 }

 else
 {
   Console.WriteLine("Error in datetime format");
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top