C#解析日期和时间

问题描述:

我在应用中的一些代码一起的C#解析日期和时间

DateTime activityDate = DateTime.Parse(tempDate + " " + tempTime); 

线凡tempDate与值,例如“2009-12-01”(即YYYY-MM-DD的字符串) 和tempTime是数值,如“23点12分10秒”(即HH字符串:MM:SS)

首先,有没有更好的方式来组合这些得到一个DateTime,其次是上面的代码可以安全地在任何地区工作(如果没有的话,是否有办法处理这个问题)

嗯看着日期更接近连接日期&时间实际上是这种格式“2009-11-26T19:37:56 + 00:00” - 日期/时间的时区部分的格式字符串是什么?

+0

(回复评论/更新) – 2010-01-08 18:52:41

如果格式是有保证,ParseExact可能会更安全(sepcifying图案):

DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime, 
    "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); 
+0

如果我在字符串中有时区信息,模式是什么 (即2009-11-26T19:37:56 + 00:00) – 2010-01-08 15:28:01

+0

对于这种模式,我会使用' XmlConvert.ToDateTime(s)',它直接处理这种格式。 – 2010-01-08 18:52:11

您可以使用ParseExact指定日期和时间格式。

如:

DateTime dateTime = 
     DateTime.ParseExact("2009-12-01 23:12:10", "yyyy-MM-dd HH:mm:ss", null); 

其中产量:

Assert.That(dateTime, Is.EqualTo(new DateTime(2009, 12, 1, 23, 12, 10))); 

你也可以指定使用这种格式的文化和解析使用它的日期和时间,同时保持解析安全从处理OS文化。
从快速浏览看,似乎没有这种精确的预定义格式的文化,但通常框架文化中存在许多标准格式。

使用ParseExact。它被问了几次在SO .. Link1,Link2

您可以使用ParseExact指定解析的格式。这样没有风险为它以其他任何方式进行解析:

DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime, "yyyy'-'MM'-'dd HH':'mm':'ss", CultureInfo.InvariantCulture); 

就好像你关心,另一种选择是做:

DateTime activityDateOnly = 
    DateTime.ParseExact(tempDate, "yyyy-MM-dd", CultureInfo.InvariantCulture); 

TimeSpan activityTime = 
    TimeSpan.ParseExact(tempTime, "hh':'mm':'ss", CultureInfo.InvariantCulture); 

DateTime activityDate = activityDateOnly + activityTime; 

只是一个选项...