将 utc-datetime 的字符串转换为 datetime-Ojbect

convert string with utc-datetime to datetime-Ojbect

首先我是 C# 新手。

我必须转换一个string喜欢

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

变成了DateTime。我试过几个格式字符串(比如"ddd, dd MMM yyyy HH:mm:ss""r""R")。但我总是收到 错误消息

String was not recognized as a valid DateTime.

这是我最后的代码:

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

感谢您的支持。

此致 Andreas## 标题 ##

正是 (UTC) 导致字符串无法被识别为时间戳。您可以通过删除它来解释 (UTC),我在这里提供了一种方法来完成此操作。

        string stringToFormat = "Fri, 30 Jul 2021 11:57:58 (UTC)";

        string[] SubString = stringToFormat.Split('(');
        stringToFormat = SubString[0].Trim();

        string timeStampFormat = "ddd, dd MMM yyyy HH:mm:ss";
        DateTime mydateTime = DateTime.ParseExact(stringToFormat, timeStampFormat, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AssumeUniversal);
        

或者将 (UTC) 替换为与 UTC 的偏移量,在本例中为 0,并将 (z) 添加到 timeStampFormat。

        string stringToFormat = "Fri, 30 Jul 2021 11:57:58 (UTC)";
        stringToFormat = stringToFormat.Replace("(UTC)", "(-0)");

        string timeStampFormat = "ddd, dd MMM yyyy HH:mm:ss (z)";
        DateTime mydateTime = DateTime.ParseExact(stringToFormat, timeStampFormat, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AssumeUniversal);
        

https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

假设你不仅可以有 (UTC),还有 (UTC+4)(UTC-5) 和类似的后缀,我建议 escaping (UTC):

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

演示:

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

结果:

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