简体   繁体   English

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

[英]DateTime.TryParse issue with dates of yyyy-dd-MM format

I have the following date in string format "2011-29-01 12:00 am" . 我有以下日期的字符串格式“ 2011-29-01 12:00 am”。 Now I am trying to convert that to datetime format with the following code: 现在,我尝试使用以下代码将其转换为日期时间格式:

DateTime.TryParse(dateTime, out dt); 

But I am alwayws getting dt as {1/1/0001 12:00:00 AM} , Can you please tell me why ? 但是我总是以{1/1/0001 12:00:00 AM}作为dt,能告诉我为什么吗? and how can I convert that string to date. 以及如何将该字符串转换为日期。

EDIT: I just saw everybody mentioned to use format argument. 编辑:我刚刚看到每个人都提到使用格式参数。 I will mention now that I can't use the format parameter as I have some setting to select the custom dateformat what user wants, and based on that user is able to get the date in textbox in that format automatically via jQuery datepicker. 我现在要提到的是,我无法使用format参数,因为我有一些设置来选择用户想要的自定义dateformat,并且基于该用户,它可以通过jQuery datepicker自动以该格式获取文本框中的日期。

This should work based on your example "2011-29-01 12:00 am" 这应基于您的示例“ 2011-29-01 12:00 am”而起作用

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

You need to use the ParseExact method . 您需要使用ParseExact方法 This takes a string as its second argument that specifies the format the datetime is in, for example: 这将字符串作为第二个参数,该字符串指定datetime的格式,例如:

// 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. 如果用户可以在UI中指定格式,则需要将其转换为可以传递给此方法的字符串。 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: 如果输入可能不正确(例如用户输入),则最好使用TryParseExact而不是使用异常来处理错误情况:

// 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. 如果您从配置文件或数据库中读取可能的格式,则可以在遇到人们想要输入日期的所有不同方式时将其添加到其中。

Try using safe TryParseExact method 尝试使用安全的TryParseExact方法

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);

From DateTime on msdn: 从msdn上的DateTime

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 . 类型:System.DateTime%当此方法返回时,如果转换成功,则包含等于s中包含的日期和时间的DateTime值;如果转换成功,则包含MinValue 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. 如果s参数为null,为空字符串(“”)或不包含日期和时间的有效字符串表示,则转换将失败。 This parameter is passed uninitialized. 该参数未初始化地传递。

Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead. 请使用parseexact,其格式字符串为"yyyy-dd-MM hh:mm tt"

这样可行:

DateTime dt = DateTime.ParseExact("2011-29-01 12:00 am", "yyyy-dd-MM hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact("11-22-2012 12:00 am", "MM-dd-yyyy 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 (ie 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. 如果让用户对日期/时间格式进行自由格式设计,则必须在运行时创建相应的DateTime格式字符串。

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

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