当前位置: 动力学知识库 > 问答 > 编程问答 >

.net - C# Date Format Conversion Error

问题描述:

This is my code.

 dateString = "6/29/2014";

format = "yy-mm-dd";

try

{

result = DateTime.ParseExact(dateString, format, provider);

Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());

}

catch (FormatException)

{

Console.WriteLine("{0} is not in the correct format.", dateString);

}

I want to convert my date 6/29/2014 to 2014-06-29 but i am getting an error that date is not in a correct format . What am i missing here?

网友答案:

Your format string doesn't match the input, and you didn't specify an output format.

var dateString = "6/29/2014";
var format = "M/dd/yyyy";  // adjusted format to match input

try
{
    var result = DateTime.ParseExact(dateString, format, provider);

    Console.WriteLine("{0} converts to {1}.",
        dateString, result.ToString("yyyy-MM-dd"));  // specify output format
}
catch (FormatException)
{
    Console.WriteLine("{0} is not in the correct format.", dateString);
}

Output:

6/29/2014 converts to 2014-06-29.

网友答案:

Couple things.

You want to pass in the format you're coming FROM to make it a date object. The "conversion" you're looking for comes out the other end. Also, you're not passing in MM/dd/yy, that date string is actually M/dd/yyyy as it doesn't include the leading zero in the month, and it's a 4-digit year.

Here's a working example.

string dateString = "6/29/2014";
string format = "M/dd/yyyy";
try
{
    DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
    Console.WriteLine("{0} converts to {1}.", dateString, result.ToString("yyyy-MM-dd"));
}
catch (FormatException)
{
    Console.WriteLine("{0} is not in the correct format.", dateString);
}

Note that I'm passing the new format into the ToString function.

网友答案:

You need to first parse the date, then to-string it.

var asDate = DateTime.Parse(dateString);
var result = asDate.ToString("yy-MM-dd");

Also note that "mm" in .NET gives you minutes. You need to use "MM" for month.

分享给朋友:
您可能感兴趣的文章:
随机阅读: