Question

I am trying to convert string to datetime. But it is giving me exceptioncontibously. Kindly help.

DateTime dt = Convert.ToDateTime("15-07-2013");

I am getting exception as "String was not recognized as a valid DateTime."

Now i have the string as "15-07-2013 07:12:00 PM" When i am using the code as mentioned below i am getting exception.

 DateTime dtCurrentFile = DateTime.ParseExact("15-07-2013 07:12:00 PM", "dd-MM-yyyy HH:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None);

I am getting the same exception.

Was it helpful?

Solution 2

You can always force the format with DateTime.ParseExact and avoid culture issues with using InvariantCulture:

DateTime dt = DateTime.ParseExact("15-07-2013", "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);

Custom Date and Time Format Strings

However, your code works for me with culture "de-DE".

Update:

You have to use lower hh for the hours when you provide the am/pm designator:

DateTime.ParseExact("15-07-2013 07:12:00 PM", "dd-MM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None)

HH means 24h format which makes no sense at all with the AM/PM designator.

OTHER TIPS

Your string format is "dd-MM-yyyy" , but Convert.ToDateTime() default format is "MM-dd-yyyy" . So Options are:

  1. Changing your string format to "07/15/2013"
  2. Forcing the conversion to adapt with it using:

    DateTime dt = DateTime.ParseExact("15-07-2013", "dd-MM-yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None);

try to use ParseExact:

DateTime dt = DateTime.ParseExact("15-07-2013", "dd-MM-yyyy", null);

The problem why you are getting exception is that by default C# supports date time in this format
"MM/dd/yyyy" where as you are trying passing date time is this format "dd-MM-yyyy"
although you can convert using your format but for that you need to tell the compiler your date is in which format so for that you can use
DateTime myDate = DateTime.ParseExact("15-07-2013", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top