【发布时间】:2016-02-15 16:12:43
【问题描述】:
如何在 C# 中将默认的 git 格式解析为 DateTime? 根据What is the format for --date parameter of git commit
git 的默认日期格式类似于Mon Jul 3 17:18:43 2006 +0200。
现在我无法控制输出,这个字符串来自另一个打印日期的工具,我需要解析它。
【问题讨论】:
标签: c# git datetime string-parsing
如何在 C# 中将默认的 git 格式解析为 DateTime? 根据What is the format for --date parameter of git commit
git 的默认日期格式类似于Mon Jul 3 17:18:43 2006 +0200。
现在我无法控制输出,这个字符串来自另一个打印日期的工具,我需要解析它。
【问题讨论】:
标签: c# git datetime string-parsing
我不会将其解析为DateTime,我会将其解析为DateTimeOffset,因为它内部有一个UTC offset 值。
为什么?因为如果您将其解析为DateTime,您将得到DateTime 作为Local 并且它可能为不同的机器生成不同的结果,因为它们可以有时区偏移那个时间。
例如,我在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);
}
现在,您有一个DateTimeOffset 作为07/03/2006 17:18:43 +02:00。您仍然可以使用 .DateTime property 获取 DateTime 部分,但在这种情况下,Kind 将是 Unspecified。
当然,我建议改用Noda Time,它可以解决大部分DateTime 的怪异问题。
【讨论】:
目前我找到的最好的格式字符串是ddd MMM d HH:mm:ss yyyy K。
DateTime date;
DateTime.TryParseExact(
gitDateString,
"ddd MMM d HH:mm:ss yyyy K",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date
);
【讨论】: