CodeInSpace
CodeInSpace

Reputation: 23

Convert.ToDateTime can't converting Day/Month/Year

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?

Upvotes: 1

Views: 662

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112382

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)

Upvotes: 2

Hossein Sabziani
Hossein Sabziani

Reputation: 3495

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);

Upvotes: 3

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);

Upvotes: -1

Related Questions