解析DateTime字符串 [英] Parsing DateTime strings

查看:150
本文介绍了解析DateTime字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用DateTime.ParseExact解析DateTime字符串有困难。

I'm having some difficulties parsing strings of DateTime using DateTime.ParseExact.

    DateTime result;
    CultureInfo provider = CultureInfo.InvariantCulture;

    // Parse date-only value with invariant culture.
    //format = "mm/dd/yyyy";
format = "d";
    try
    {

        result = DateTime.ParseExact(data+" 12:00:00 AM", format, provider);
    }

数据是一个字符串变量,日期格式为5/20 / 2009。我试图抓住一个假的时间,只是为了看看是否会起作用,而没有(有或没有的)。我也尝试使用g格式说明符,它没有工作,我总是得到异常,它不是一个有效的DateTime字符串。它唯一的工作日期就像12/20/2009(注意MM部分的2位数字)

data is a string variable loaded with dates of the format "5/20/2009". I tried tacking on a fake time just to see if that would work, and it didn't(with or without the tack on). I also tried using the "g" format specifier and it did not work, I always get the exception that it isn't a valid DateTime string. The only dates it works for is like "12/20/2009" (notice that 2 digits in the "MM" part)

我无法让这个例程工作单位数月微软自己的MSDN示例是

I can not get this routine to work with single digit months! Microsofts own example from MSDN is

6/15/2009 1:45:30 PM -> 6/15/2009 (en-US)

,它不会用于此。我只是不明白我在做错什么我也尝试过我自己的格式说明符,如mm / dd / yyyy和MM / dd / yyyy,但没有效果。

and it will not work with this. I am just not understanding what I am doing wrong. I have also tried my own format specifiers like "mm/dd/yyyy" and "MM/dd/yyyy" but to no avail.

推荐答案

如果您要以en-US格式解析DateTime,则必须指定en-US文化: p>

If you want to parse a DateTime in en-US format, you have to specify the en-US culture:

DateTime.ParseExact("6/15/2009", "d", CultureInfo.GetCultureInfo("en-US"));

这篇关于解析DateTime字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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