DateTime.TryParseExact添加一分钟? [英] DateTime.TryParseExact adds one minute?

查看:125
本文介绍了DateTime.TryParseExact添加一分钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个转换:

DateTime dateTime;
DateTime.TryParseExact("01/02/2013", "mm/dd/yyyy", null, DateTimeStyles.None, out dateTime);

以下Assert失败:

The following Assert fails:

Assert.AreEqual(new DateTime(2013, 1, 2), dateTime);

由于TryParseExact为datetime添加了一个小时:

Because TryParseExact adds one hour to the datetime:

Expected: 2013-01-02 00:00:00.000
But was:  2013-01-02 00:01:00.000

这是否与夏令时相关,如果是,那是否意味着我不应该使用DateTimeStyles.None?

Is this related to daylight savings time, and if so, does that mean I shouldn't be using DateTimeStyles.None?

推荐答案

您的格式mm / dd / yyyy表示分钟 /天/年。你想要MM / dd / yyyy(大写为月)。另外,通过传递 null 你实际上说:使用当前文化的datetime格式。你可能想要使用 CultureInfo.InvariantCulture

Your format "mm/dd/yyyy" means minutes/days/years. You want "MM/dd/yyyy" (uppercase for month). Also, by passing null you actually say: use the current culture's datetime format. You probably want to use CultureInfo.InvariantCulture.

DateTime.TryParseExact("01/02/2013", "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);

如果当前文化不使用 / 作为日期分隔符。例如,德国使用作为分隔符,因此格式字符串MM / dd / yyyy将是评估为MM.dd.yyyy 阅读

This also prevents issues if the current culture does not use / as date-separator. Germany, for example, uses . as separator, hence the format-string "MM/dd/yyyy" would be evaluated as "MM.dd.yyyy". Read.

这篇关于DateTime.TryParseExact添加一分钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆