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

我有2个DateTime对象,使用ToShortDateString()函数后保存到文件中; 字符串看起来像“12/15/2009”。 我现在卡在这一部分,我想用这些字符串初始化DateTime对象,以便我可以比较日期日期之间的时间跨度。 任何帮助赞赏。

你可以试试

DateTime date = DateTime.ParseExact("12/15/2009", "MM/dd/yyyy", null); 

看一下

  • DateTime.ParseExact方法(String,String,IFormatProvider)
  • Easy String to DateTime,DateTime to String和Formatting

假设您正在以字符串格式从文件中读回日期

 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转换时,我通常会尝试坚持这一点:

  • 以文本格式保存日期时,请明确格式化。 优选地采用标准化格式(例如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); } 

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

提取年,月和日,而不是像使用smth一样:

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

或克里特岛一种扩展方法来转换回日期时间这种字符串,但一般来说,那个扩展名美联体的主体就像这样。