DateTime.TryParse 世纪控件 C# [英] DateTime.TryParse century control C#

查看:21
本文介绍了DateTime.TryParse 世纪控件 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段的结果是12/06/1930 12:00:00".我如何控制隐含的世纪,以便30 年 6 月 12 日"变成 2030 年?

The result of the following snippet is "12/06/1930 12:00:00". How do I control the implied century so that "12 Jun 30" becomes 2030 instead?

    string dateString = "12 Jun 30"; //from user input
    DateTime result;
    DateTime.TryParse(dateString, new System.Globalization.CultureInfo("en-GB"),System.Globalization.DateTimeStyles.None,out result);
    Console.WriteLine(result.ToString());

请暂时搁置正确的解决方案是首先正确指定日期这一事实.

Please set aside, for the moment, the fact that a correct solution is to specify the date correctly in the first place.

注意:结果与运行代码的电脑的系统日期时间无关.

Note: The result is independant of the system datetime for the pc running the code.

答案:谢谢 Deeksy

Answer: Thanks Deeksy

    for (int i = 0; i <= 9; i++)
    {
        string dateString = "12 Jun " + ((int)i * 10).ToString();
        Console.WriteLine("Parsing " + dateString);
        DateTime result;
        System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-GB");
        cultureInfo.Calendar.TwoDigitYearMax = 2099;
        DateTime.TryParse(dateString, cultureInfo , System.Globalization.DateTimeStyles.None, out result);
        Console.WriteLine(result.ToString());
    }

推荐答案

这很棘手,因为两位数年份与 TryParse 一起使用的方式基于您正在使用的 CultureInfo 对象的 Calendar 属性的 TwoDigitYearMax 属性.(CultureInfo->Calendar->TwoDigitYearMax)

It's tricky, because the way two digit years work with TryParse is based on the TwoDigitYearMax property of the Calendar property of the CultureInfo object that you are using. (CultureInfo->Calendar->TwoDigitYearMax)

为了使两位数的年份在前面加上 20,您需要手动创建一个 CultureInfo 对象,该对象具有一个将 2099 设置为 TwoDigitYearMax 属性的 Calendar 对象.不幸的是,这意味着解析的任何两位数日期都会有 20(包括 98、99 等),这可能不是您想要的.

In order to make two digit years have 20 prepended, you'll need to manually create a CultureInfo object which has a Calendar object with 2099 set as the TwoDigitYearMax property. Unfortunately, this means that any two digit date parsed will have 20 prepended (including 98, 99 etc.) which is probably not what you want.

我怀疑您最好的选择是使用第 3 方日期解析库,而不是使用 +50/-50 年规则表示 2 位数年份的标准 tryparse.(2 位数的年份应转换为今年之前 50 年和比今年大 50 年之间的范围).

I suspect that your best option is to use a 3rd party date parsing library instead of the standard tryparse that will use the +50/-50 year rule for 2 digit years. (that a 2 digit year should be translated into a range between 50 years before this year and 50 years greater than this year).

或者,您可以覆盖日历对象(它是虚拟的)上的 ToFourDigitYear 方法并使用它来实现 -50/+50 规则.

这篇关于DateTime.TryParse 世纪控件 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆