1

Format: Day/Month/Year - C#

Console.WriteLine(Convert.ToDateTime("28.12.2022 13:45:04")); //Error

It throws

System.FormatException: String was not recognized as a valid DateTime

I couldn't find a solution for this. Can you help me?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

3 Answers3

3

DateTime.ParseExact Converts the specified string representation of a date and time to its DateTime equivalent.

DateTime dt= DateTime.ParseExact("28.12.2022 13:45:04", "dd.MM.yyyy HH:mm:ss",
                                  CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Hossein Sabziani
  • 1
  • 2
  • 15
  • 20
2

Specify the culture corresponding to your date/time format. Example:

CultureInfo culture = CultureInfo.GetCultureInfo("de-DE");
var date = DateTime.Parse(dateString, culture);

However, it is safer to use TryParse than Parse:

If (DateTime.TryParse(dateString, culture, out var date)) {
    Console.WriteLine(date);
} else {
    Console.WriteLine("Invalid date format");
}

Note, Parse and TryParse recognize a wider range of formats than ParseExact and TryParseExact. The former also work if, for example, the time part is missing or the date contains a month name.

See also: When to use CultureInfo.GetCultureInfo(String) or CultureInfo.CreateSpecificCulture(String)

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
-1

You can get short date string like "28/12/2022" a string. Using;

yourDateTime.Value.ToShortDateString();

Localization about your computer setting. It can be change type of your date format. You can use;

yourDatetime.Value.ToString("dd/MM/yyyy");

String to DateTime

DateTime dt= DateTime.ParseExact("datetimeString", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);