gpt4 book ai didi

c# - 如何在 C# 中解析默认的 git 日期格式

转载 作者:太空狗 更新时间:2023-10-29 14:05:34 25 4
gpt4 key购买 nike

如何在 C# 中将默认的 git 格式解析为 DateTime?根据 What is the format for --date parameter of git commit

git 的默认日期格式类似于 Mon Jul 3 17:18:43 2006 +0200

现在我无法控制输出,这个字符串来自另一个打印日期的工具,我需要解析它。

最佳答案

我不会将其解析为 DateTime,我会将其解析为 DateTimeOffset因为它有一个 UTC offset里面的值(value)。

为什么?因为如果您将它解析为 DateTime,您将得到一个作为 LocalDateTime,它可能为不同的机器,因为它们可以具有那个时间的时区偏移量。

例如,我在 Istanbul我们使用 Eastern European Time使用 UTC+02:00。如果我使用 ParseExact 方法运行您的代码示例,我将获得 07/03/2006 18:18:43 作为 Local时间。

为什么?因为在 2006 年 7 月 3 日,my timezone was in a daylight saving time这是 UTC+03:00。这就是它生成 1 小时转发结果的原因。当您将它解析为 DateTime 时,这就是它变得模棱两可的部分。

string s = "Mon Jul 3 17:18:43 2006 +0200";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(s, "ddd MMM d HH:mm:ss yyyy K",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}

现在,您的 DateTimeOffset07/03/2006 17:18:43 +02:00。您仍然可以通过它的 .DateTime property 获得 DateTime 部分但它是Kind在那种情况下将是 Unspecified

当然,我建议使用 Noda Time相反,它可以解决大部分日期时间问题。

关于c# - 如何在 C# 中解析默认的 git 日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33703599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com