C#解析日期和时间

C#解析日期和时间,c#,C#,我在应用程序中有一些代码 DateTime activityDate = DateTime.Parse(tempDate + " " + tempTime); 其中,tempDate是一个字符串,其值为“2009-12-01”(即yyyy-mm-dd) TENTIME是一个字符串,其值为“23:12:10”(即hh:mm:ss) 首先,有没有更好的方法将它们结合起来以获得日期时间,其次,上面的代码在任何区域都可以安全地工作(如果没有,是否有方法处理此问题) 嗯,更仔细地看一下日期连接的日期和时

我在应用程序中有一些代码

DateTime activityDate = DateTime.Parse(tempDate + " " + tempTime);
其中,tempDate是一个字符串,其值为“2009-12-01”(即yyyy-mm-dd) TENTIME是一个字符串,其值为“23:12:10”(即hh:mm:ss)

首先,有没有更好的方法将它们结合起来以获得日期时间,其次,上面的代码在任何区域都可以安全地工作(如果没有,是否有方法处理此问题)

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

您可以用来指定日期和时间格式

e、 g:

这将产生:

Assert.That(dateTime, Is.EqualTo(new DateTime(2009, 12, 1, 23, 12, 10)));
您还可以指定使用此格式的区域性,并使用该格式解析日期和时间,同时确保解析不受处理操作系统区域性的影响。

快速查看,似乎没有使用此精确预定义格式的区域性,但通常框架区域性中存在许多标准格式。

如果格式得到保证,
ParseExact
可能更安全(指定模式):


使用ParseExact。这已经被问了好几次了所以

您可以使用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;

只是一个选项…

如果字符串中有时区信息,那么该模式的模式是什么(即2009-11-26T19:37:56+00:00),我将使用直接处理此格式的
XmlConvert.ToDateTime
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;