DateTime Parse character escape with \\ succeeds in .NET Framework, but fails in .NET 6.0

Viewed 32

The following code succeeds in online IDE (mono-6.12.0) or in .NET Framework 4.7.2, but fails in Microsoft .NET 6.0 with the error message below. How to make it work in .NET 6.0?

Unhandled exception. System.FormatException: String 'Sat Sep 10 05:57:59 KST 2022' was not recognized as a valid DateTime.

at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)

Code

var data = "Sat Sep 10 05:57:59 KST 2022";
var time = DateTime.ParseExact(data, "ddd MMM d hh:mm:ss \\K\\S\\T yyyy", null);

Console.WriteLine(time);
1 Answers

I would suggest using InvariantCulture

var data = "Sat Sep 10 05:57:59 KST 2022";

var time = DateTime.ParseExact(
    data,
    "ddd MMM d hh:mm:ss \\K\\S\\T yyyy",
    CultureInfo.InvariantCulture);
Console.WriteLine(time);

Will give output

10-09-2022 05:57:59

enter image description here

Related