我有两个DateTime对象,使用ToShortDateString()函数后保存到文件中的字符串看起来像"12/15/2009"。现在我卡住了,我想初始化DateTime对象,以便可以比较日期之间的时间跨度。感谢任何帮助。
你可以尝试
DateTime date = DateTime.ParseExact("12/15/2009", "MM/dd/yyyy", null);
请看
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);
在处理 DateTime
/string
转换时,我通常遵循以下原则:
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);
}
DateTime.Parse(str)
吗?提取年、月和日,然后使用类似以下的代码:
var dt = new DateTime(Year,Month,Day)
或者创建一个扩展方法来将这种字符串转换回DateTime,但通常该扩展方法的主体会像这样。
M/d/yyyy
来修复,不过更安全的做法是使用CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
,因为这是ToShortDateString()
所使用的模式,其文档中有记录。 - undefined