简体   繁体   English

将字符串解析为DateTime对象

[英]Parse a string to a DateTime object

I'm trying to parse a String into a DateTime object but it seems to always default the month to 1. So let's say I give it a string 30/05/1970 it ends up being converted to DateTime object with the month value equal to 1 . 我试图解析StringDateTime对象,但它似乎总是默认月份为1。所以我们可以说我给它一个字符串30/05/1970它最终被转换成DateTime对象与月份值等于1

Here's the code: 这是代码:

    public static DateTime ToDateTime(this String value, String format)
    {
        Contract.Requires(!String.IsNullOrEmpty(value));
        Contract.Requires(!String.IsNullOrEmpty(format));

        DateTime date;
        if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
        {
            return date;
        }           

        throw new ArgumentException("Input value is not a valid date.");
    }

Note that the format that is being passed to the method is dd/mm/yyyy . 请注意,传递给该方法的格式为dd/mm/yyyy

Any thoughts? 有什么想法吗?

You are using the wrong format specifier for months. 您使用错误的格式说明符已有几个月了。

It is MM not mm . MM不是mm You are parsing months as minutes at the moment. 您现在将月份解析为分钟。

Use dd/MM/yyyy . 使用dd/MM/yyyy

You're probably specifying an incorrect format. 您可能指定了错误的格式。

Do this instead 改为这样做

var dt= ToDateTime("30/05/1970", "dd/MM/yyyy");

And take a look at this: http://www.csharp-examples.net/string-format-datetime/ 并查看以下内容: http : //www.csharp-examples.net/string-format-datetime/

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

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