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

发布于 2024-10-12 15:18:40 字数 320 浏览 2 评论 0原文

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

DateTime.TryParse(dateTime, out dt); 

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

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

I have the following date in string format "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 ? 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

2024-10-19 15:18:40

这应该基于您的示例“2011-29-01 12:00 am”

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

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);
陌若浮生 2024-10-19 15:18:40

您需要使用 ParseExact 方法 。这将字符串作为第二个参数,指定日期时间的格式,例如:

// Parse date and time with custom specifier.
CultureInfo provider = CultureInfo.InvariantCulture;
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);
}

如果用户可以在 UI 中指定格式,那么您需要将其转换为可以传递到此方法的字符串。您可以通过允许用户直接输入格式字符串(尽管这意味着转换更有可能失败,因为他们输入无效的格式字符串)或者使用一个组合框来实现这一点它们包含可能的选择,并且您为这些选择设置格式字符串。

如果输入可能不正确(例如用户输入),最好使用 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);
}

更好的替代方案可能是 not< /strong> 向用户提供日期格式选择,但使用 采用一系列格式的重载

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

如果您从配置文件或数据库中读取可能的格式,那么您可以在遇到所有不同的方式时添加到这些格式人们想要输入日期。

这种方法的主要缺点是日期仍然不明确。这些格式是按顺序尝试的,因此无论什么格式,它都会在美国格式之前尝试欧洲格式(反之亦然),并涵盖欧洲格式日期中日期小于 13 的任何内容,即使用户认为他们输入的是美国格式格式化日期。

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.
CultureInfo provider = CultureInfo.InvariantCulture;
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.

临走之时 2024-10-19 15:18:40

尝试使用安全的 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);

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);
简美 2024-10-19 15:18:40

来自 msdn 上的 DateTime

类型:System.DateTime% 当此方法返回时,包含 DateTime
值等于 s 中包含的日期和时间,如果
转换成功,或MinValue(如果转换失败)。这
如果 s 参数为 null,则转换失败,是一个空字符串 (""),
或者不包含日期和时间的有效字符串表示形式。
该参数在未初始化的情况下传递。

请改用带有格式字符串 "yyyy-dd-MM hh:mm tt" 的 parseexact。

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.

⒈起吃苦の倖褔 2024-10-19 15:18:40

有效:

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

That works:

DateTime dt = DateTime.ParseExact("2011-29-01 12:00 am", "yyyy-dd-MM hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
南…巷孤猫 2024-10-19 15:18:40
DateTime dt = DateTime.ParseExact("11-22-2012 12:00 am", "MM-dd-yyyy 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);
╭ゆ眷念 2024-10-19 15:18:40

如果您为用户提供更改日期/时间格式的机会,那么您必须创建相应的格式字符串以用于解析。如果您知道可能的日期格式(即用户必须从列表中选择),那么这会容易得多,因为您可以在编译时创建这些格式字符串。

如果您让用户对日期/时间格式进行自由格式设计,那么您必须在运行时创建相应的 DateTime 格式字符串。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文