-3

I want compare the date by first converting the string "14012019" to Datetime

This is the code that I have tried

DateTime dateTime = DateTime.Parse("14012019");

and

 DateTime dateTime = DateTime.ParseExact("14012019", "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None);

and

Convert.ToDateTime("14012019")

This is the error I'm getting String was not recognized as a valid DateTime Exception.

  • Have a closer look at the date string, and think about where the various components are – Matthew Watson Jan 14 '19 at 09:10
  • You are almost there. [DateTime.ParseExact](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netframework-4.7.2#System_DateTime_ParseExact_System_String_System_String_System_IFormatProvider_) is exactly what you need – vasily.sib Jan 14 '19 at 09:10
  • 6
    `DateTime dateTime = DateTime.ParseExact("14012019", "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);` – ES2018 Jan 14 '19 at 09:10
  • 1
    Possible duplicate of [Converting a String to DateTime](https://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – bit Jan 14 '19 at 09:11
  • 4
    You should try to understand what the `yyyy`,`MM`,`dd`,`HH`,`mm`,`ss` actually mean. If you don't understand it you will never be able to solve such tasks yourself. Read: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings – Tim Schmelter Jan 14 '19 at 09:13

1 Answers1

6
 DateTime dateTime = DateTime.ParseExact("14012019", "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None);

Needs to be

 DateTime dateTime = DateTime.ParseExact("14012019", "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);

Your order of month / day / year was wrong in the method .ParseExact()

Kahn Kah
  • 1,389
  • 7
  • 24
  • 49