Search code examples
c#datetimedatetime-formatutc

convert string with utc-datetime to datetime-Ojbect


First of all I am new in C#.

I have to convert a string like

  "Fri, 30 Jul 2021 11:57:58 (UTC)" 

into a DateTime. I've tried serveral format strings (like "ddd, dd MMM yyyy HH:mm:ss", "r", "R"). But I always get the error message

String was not recognized as a valid DateTime.

Here is my last code for this:

CultureInfo enUS = new CultureInfo("en-US");
string timeStampFormat = "ddd, dd MMM yyyy HH:mm:ss";
DateTime myDateTime;

myDateTime = DateTime.ParseExact(
  stringToFormat, 
  timeStampFormat, 
  enUS, 
  DateTimeStyles.AssumeUniversal);

Thanks for your support.

Best regards Andreas## Heading ##


Solution

  • Assuming that you can have not only (UTC), but (UTC+4), (UTC-5) and alike suffixes, I suggest escaping (UTC and ):

      string stringToFormat = "Fri, 30 Jul 2021 11:57:58 (UTC)";
    
      ...
    
      DateTime myDateTime = DateTime.ParseExact(
        stringToFormat, 
        new string[] { 
          "ddd, d MMM yyyy H:m:s '(UTC)'",
          "ddd, d MMM yyyy H:m:s '(UTC'z')'",
        },
        CultureInfo.GetCultureInfo("en-US"),
        DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
    

    Demo:

      DateTime demo(string text) => DateTime.ParseExact(
        text, 
        new string[] { 
          "ddd, d MMM yyyy H:m:s '(UTC)'",
          "ddd, d MMM yyyy H:m:s '(UTC'z')'",
        },
        CultureInfo.GetCultureInfo("en-US"),
        DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
    
      string[] tests = new string[] {
        "Fri, 30 Jul 2021 11:57:58 (UTC)",
        "Fri, 30 Jul 2021 11:57:58 (UTC-1)",
        "Fri, 30 Jul 2021 11:57:58 (UTC+1)",
        "Fri, 30 Jul 2021 11:57:58 (UTC-14)",
      };
    
      string report = string.Join(Environment.NewLine, tests
        .Select(test => $"{test,-40} => {demo(test):dd.MM.yyyy HH:mm:ss}"));
    
      Console.Write(report);
    

    Outcome:

    Fri, 30 Jul 2021 11:57:58 (UTC)          => 30.07.2021 11:57:58
    Fri, 30 Jul 2021 11:57:58 (UTC-1)        => 30.07.2021 12:57:58
    Fri, 30 Jul 2021 11:57:58 (UTC+1)        => 30.07.2021 10:57:58
    Fri, 30 Jul 2021 11:57:58 (UTC-14)       => 31.07.2021 01:57:58