Search code examples
c#datetimedatetime-formaticalendar

c# Datetime not recognized as a valid DateTime


I am trying read an Icalendar file but here is the error I am getting: I am using Godot 4.2, but that shouldn't make a difference I think.

E 0:00:00:0432   System.DateTime System.DateTime.ParseExact(string, string, System.IFormatProvider): System.FormatException: String '20231120T153000' was not recognized as a valid DateTime.
  <C++ Error>    System.FormatException
  <C++ Source>   :0 @ System.DateTime System.DateTime.ParseExact(string, string, System.IFormatProvider)
  <Stack Trace>  :0 @ System.DateTime System.DateTime.ParseExact(string, string, System.IFormatProvider)
                 Application.cs:77 @ System.DateTime Application.ParseICSDateTime(string)
                 Application.cs:49 @ void Application.ReadFile(string)
                 Application.cs:23 @ void Application._Ready()
                 Node.cs:2117 @ bool Godot.Node.InvokeGodotClassMethod(Godot.NativeInterop.godot_string_name&, Godot.NativeInterop.NativeVariantPtrArgs, Godot.NativeInterop.godot_variant&)
                 CanvasItem.cs:1368 @ bool Godot.CanvasItem.InvokeGodotClassMethod(Godot.NativeInterop.godot_string_name&, Godot.NativeInterop.NativeVariantPtrArgs, Godot.NativeInterop.godot_variant&)
                 Control.cs:2841 @ bool Godot.Control.InvokeGodotClassMethod(Godot.NativeInterop.godot_string_name&, Godot.NativeInterop.NativeVariantPtrArgs, Godot.NativeInterop.godot_variant&)
                 Application_ScriptMethods.generated.cs:58 @ bool Application.InvokeGodotClassMethod(Godot.NativeInterop.godot_string_name&, Godot.NativeInterop.NativeVariantPtrArgs, Godot.NativeInterop.godot_variant&)
                 CSharpInstanceBridge.cs:24 @ Godot.NativeInterop.godot_bool Godot.Bridge.CSharpInstanceBridge.Call(nint, Godot.NativeInterop.godot_string_name*, Godot.NativeInterop.godot_variant**, int, Godot.NativeInterop.godot_variant_call_error*, Godot.NativeInterop.godot_variant*)

The way I am parsing:

In the comments I put the 'invalid' date time, the underscores are for readability.

private const string DATE_TIME_FORMAT = "yyyyMMddThhmmss";

private static DateTime ParseICSDateTime(string line)
{
    // 2023_11_20_T_15_30_00
    // yyyy_MM_dd_T_hh_mm_ss
    
    string dateTimeString = line.Split(":")[1];
    GD.Print(dateTimeString);
    
    DateTime result = DateTime.ParseExact(dateTimeString, DATE_TIME_FORMAT, CultureInfo.InvariantCulture);
    return result;
}

I am not sure why this date time in particular is invalid since for others it works fine. See the image of the console Console screenshot

I tried the null IFormatProvider but that also didn't work.

I also tried removing the T inside of the dateTimeString but again, no dice.


Solution

  • The hours format should be "HH" for 24 hours time instead of hh (12 hours repeated for AM and PM).

    private const string DATE_TIME_FORMAT = "yyyyMMddTHHmmss";