具有 yyyy-dd-MM 格式日期的 DateTime.TryParse 问题

我有以下日期在字符串格式“2011-29-01上午12:00”。现在我尝试用以下代码将其转换为日期时间格式:

DateTime.TryParse(dateTime, out dt);

但是我总是得到 dt 作为{1/1/000112:00:00 AM } ,你能告诉我为什么吗?以及如何将该字符串转换为日期。

编辑: 我刚刚看到每个人都提到要使用格式参数。现在我要提到的是,我不能使用 format 参数,因为我有一些设置来选择用户想要的自定义日期格式,并且基于这个用户能够通过 jQuery 数据采集器自动获取文本框中的日期。

212803 次浏览

From DateTime on msdn:

Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.

You need to use the ParseExact method. This takes a string as its second argument that specifies the format the datetime is in, for example:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
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);
}

If the user can specify a format in the UI, then you need to translate that to a string you can pass into this method. You can do that by either allowing the user to enter the format string directly - though this means that the conversion is more likely to fail as they will enter an invalid format string - or having a combo box that presents them with the possible choices and you set up the format strings for these choices.

If it's likely that the input will be incorrect (user input for example) it would be better to use TryParseExact rather than use exceptions to handle the error case:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
DateTime result;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out result))
{
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
else
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}

A better alternative might be to not present the user with a choice of date formats, but use the overload that takes an array of formats:

// A list of possible American date formats - swap M and d for European formats
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
"MM/d/yyyy HH:mm:ss.ffffff" };
string dateString; // The string the date gets read into


try
{
dateValue = DateTime.ParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None);
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}

If you read the possible formats out of a configuration file or database then you can add to these as you encounter all the different ways people want to enter dates.

The main drawback with this approach is that you will still have ambiguous dates. The formats are tried in order so no matter what it'll try the European format before the American (or vice versa) and cover anything where the day is less than 13 to a European formatted date even if the user thought they were entering an American formatted date.

This should work based on your example "2011-29-01 12:00 am"

DateTime dt;
DateTime.TryParseExact(dateTime,
"yyyy-dd-MM hh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);

That works:

DateTime dt = DateTime.ParseExact("2011-29-01 12:00 am", "yyyy-dd-MM hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);

If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.

If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.

Try using safe TryParseExact method

DateTime temp;
string   date = "2011-29-01 12:00 am";


DateTime.TryParseExact(date, "yyyy-dd-MM hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp);
DateTime dt = DateTime.ParseExact("11-22-2012 12:00 am", "MM-dd-yyyy hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);