Home > Enterprise >  Convert.ToDateTime can't converting Day/Month/Year
Convert.ToDateTime can't converting Day/Month/Year

Time:12-28

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?

CodePudding user response:

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",
                                   System.Globalization.CultureInfo.InvariantCulture);

        Console.WriteLine(dt);

CodePudding user response:

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