简体   繁体   English

C#中的Datetime转换问题

[英]Problem in Datetime conversion in c#

I have a problem while converting a string whose value is dd.mm.yyyy to DateTime in c# 在将C#中值为dd.mm.yyyy的字符串转换为DateTime遇到问题

string OriginalDateFormat = "28.06.2009";
DateTime dt= Convert.ToDateTime(OriginalDateFormat);

Throwing an exception "String was not recognized as a valid DateTime." 引发异常"String was not recognized as a valid DateTime."

But if it is in mm.dd.yyyy then it is running fine. 但是,如果它在mm.dd.yyyy ,则运行正常。

I googled and got lots of sites but all in vain 我在Google上搜索了很多网站,但都无济于事

Any idea? 任何想法?

Thanks in advance. 提前致谢。

Use DateTime.ParseExact and specify the exact format string: 使用DateTime.ParseExact并指定确切的格式字符串:

DateTime dt = DateTime.ParseExact("28.06.2009", "dd'.'MM'.'yyyy",
                                  CultureInfo.InvariantCulture);

If this is the value is from user input, you probably want to use DateTime.TryParseExact so you can handle failure gracefully: 如果这是来自用户输入的值,则可能要使用DateTime.TryParseExact,以便可以正常处理失败:

DateTime dt;
if (DateTime.TryParseExact("28.06.2009", "dd'.'MM'.'yyyy",
                        CultureInfo.InvariantCulture, 
                        DateTimeStyles.None, // Default formatting options
                        out dt))
{
    Console.WriteLine("Successfully parsed {0}", dt);
}
else
{
    Console.WriteLine("Did not recognise date");
}

I think its an issue with culture...The format you specified is (I think) GB and the default culture is US. 我认为这与文化有关...您指定的格式是(我认为)GB,默认文化是美国。 You will need to specify the culture also. 您还需要指定文化。

Instead try this: 而是尝试以下方法:

IFormatProvider culture = new CultureInfo("en-US", true);//en-Us or en-GB not sure

DateTime dt = DateTime.Parse(p, culture, DateTimeStyles.AssumeLocal);

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

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