简体   繁体   English

为什么不将该字符串转换为DateTime?

[英]Why won't this string be converted to DateTime?

2/22/2012 3:30:00 2/22/2012 3:30:00

Surely that is an acceptable format to be converted to DateTime using Convert.ToDateTime()? 肯定是可以通过Convert.ToDateTime()转换为DateTime的可接受格式吗?

I would personally avoid using Convert.ToDateTime . 我个人将避免使用Convert.ToDateTime I generally prefer 1 to use DateTime.TryParseExact , specifying the culture and format string you expect - assuming you have an expected format, of course. 我通常更喜欢1使用DateTime.TryParseExact ,指定您期望的区域性和格式字符串-当然,假设您具有期望的格式。 If you don't, you have to ask yourself bigger questions. 如果不这样做,则必须问自己更大的问题。

For example: 例如:

DateTime value;
if (DateTime.TryParseExact(text, "M/d/yyyy H:mm:ss",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out value))
{
    Console.WriteLine("Parsed to {0}", value);
}
else
{
    Console.WriteLine("Failed to parse");
}

That's a slightly odd format to start with - normally a 24-hour format would include a leading 0 for the hour, and a 12-hour format would include an am/pm designator. 开头的格式有点奇怪-通常24小时制会包含小时的前导0,而12小时制会包含am / pm指示符。


1 Well, I prefer to use Noda Time , but that's a different matter... 1好吧,我更喜欢使用Noda Time ,但这是另一回事...

Surely that is an acceptable format to be converted to DateTime using Convert.ToDateTime()? 肯定是可以通过Convert.ToDateTime()转换为DateTime的可接受格式吗?

Surely not. 当然不是。 That would be true for some locales but for example I have a fr-FR locale and this is an invalid date. 在某些语言环境中确实如此,但是例如我有一个fr-FR语言环境,这是一个无效的日期。 There are no 22 months in the year. 一年中没有22个月。 Make sure you specify the format when parsing the date. 确保在解析日期时指定格式。 You could use the TryParseExact method for this. 您可以为此使用TryParseExact方法。

If you got the Information about Year, Month, etc. separately as Integers I would rather use the Constructor of DateTime. 如果您以整数形式分别获得有关Year,Month等的信息,我宁愿使用DateTime的构造方法。

DateTime myDateTime  = new DateTime(year, month, day, hour, minute, second);

Usually nothing can go wrong with this... 通常,这没有什么错...

如果您提供一个指定区域性的IFormatProvider,则应该能够(例如,在这种情况下为en-US)。

var date = Convert.ToDateTime("2/22/2012 3:30:00", CultureInfo.GetCultureInfo("en-US"));

Here is an example on how to use Convert.ToDateTime() which will help you to understand it : 这是有关如何使用Convert.ToDateTime()的示例,它将帮助您理解它:
Convert.ToDateTime example Convert.ToDateTime示例

Or You can try by following this example : 或者您可以按照以下示例尝试:
Convert String to DateTime 将字符串转换为DateTime

This works just fine for me: 这对我来说很好:

            DateTime dt = Convert.ToDateTime("2/22/2012 3:30:00");
        Console.WriteLine(dt.ToShortDateString());
        Console.WriteLine(dt.ToShortTimeString());

Of course I am not paying attention to localization like Darin suggests 我当然不会像达林建议的那样关注本地化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM