如何将短日期字符串转换回DateTime对象?

6

我有两个DateTime对象,使用ToShortDateString()函数后保存到文件中的字符串看起来像"12/15/2009"。现在我卡住了,我想初始化DateTime对象,以便可以比较日期之间的时间跨度。感谢任何帮助。

5个回答

11

根据当前的文化背景,如果月份或日期是个位数,这种方式往往会失败。你可以使用M/d/yyyy来修复,不过更安全的做法是使用CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern,因为这是ToShortDateString()所使用的模式,其文档中有记录。 - undefined

3
假设您正在以字符串格式从文件中读取日期。
string date1 = "28/12/2009"; //this will be from your file
string date2 = "29/12/2009"; //this will be from your file
DateTime d1 = DateTime.ParseExact(date1,"dd/MM/yyyy", null);
DateTime d2 = DateTime.ParseExact(date2, "dd/MM/yyyy", null);
TimeSpan t1 = d2.Subtract(d1);

1

在处理 DateTime/string 转换时,我通常遵循以下原则:

  • 将日期以文本格式持久化时,明确指定其格式。最好使用标准化格式(例如 ISO 8601)。
  • 读取日期时,使用相同的、明确定义的格式将其解析为 DateTime 对象。

这样,您的代码就不会在使用日期格式与您不同的地方出现故障,或者如果文件在一个区域设置中创建,然后在另一个区域设置中解析,则也不会出现问题。

private static string DateToString(DateTime input)
{
    return input.ToString("yyyy-MM-dd");
}

private static DateTime StringToDate(string input)
{
    return DateTime.ParseExact(input, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}

1
你尝试过 DateTime.Parse(str) 吗?

1
根据我的经验,在这种情况下可能行不通,因为提供的格式是dd/MM/yyyy,很可能会得到一个字符串无法识别为有效日期时间的错误。DateTime.Parse(str)适用于格式为yyyy/MM/dd的字符串。 - Kamal

0

提取年、月和日,然后使用类似以下的代码:

var dt = new DateTime(Year,Month,Day)

或者创建一个扩展方法来将这种字符串转换回DateTime,但通常该扩展方法的主体会像这样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接