当前位置: 首页 > 编程语言 > C#

DateTime.TryParseCenturyControlC#分享

时间:2023-04-10 23:17:04 C#

DateTime.TryParseCenturyControlC#下面代码段的结果是“12/06/193012:00:00”。我如何控制隐含世纪以使“12月30日”变为2030年?stringdateString="12Jun30";//来自用户输入的日期时间结果;DateTime.TryParse(dateString,newSystem.Globalization.CultureInfo("en-GB"),System.Globalization.DateTimeStyles.None,outresult);控制台.WriteLine(result.ToString());请暂时搁置正确的解决方案是首先正确指定日期这一事实。注意:结果与运行代码的pc的系统日期时间无关。回答:感谢Deeksy(inti=0;i<=9;i++){stringdateString="12Jun"+((int)i*10).ToString();Console.WriteLine("解析"+dateString);日期时间结果;System.Globalization.CultureInfocultureInfo=newSystem.Globalization.CultureInfo("en-GB");cultureInfo.Calendar.TwoDigitYearMax=2099;DateTime.TryParse(dateString,cultureInfo,System.Globalization.DateTimeStyles.None,输出结果);Console.WriteLine(result.ToString());这很棘手,因为您使用TryParse的两位数年份的方式是基于您正在使用的CultureInfo对象的Calendar属性的TwoDigitYearMax属性。(CultureInfo->Calendar->TwoDigitYearMax)为了将两位数年份前面加上20,您需要手动创建一个CultureInfo对象,该对象的Calendar对象设置为2099作为TwoDigitYearMax属性。不幸的是,这意味着解析的任何两位数日期都将有20个前缀(包括98、99等),这可能不是您想要的。我怀疑你最好的选择是使用第三方日期解析库而不是标准的tryparse,它将对2位数字使用+50/-50年规则。(2位数年份应转换为今年前50年和今年第50年之间的范围)。或者,您可以覆盖日历对象(它是虚拟的)上的ToFourDigitYear方法并使用它来实现-50/+50规则。我写了一个可重用的函数:publicstaticobjectConvertCustomDate(stringinput){//根据我们当前的文化创建一种新文化,但覆盖两位//digitye??armax。CultureInfoci=newCultureInfo(CultureInfo.CurrentCulture.LCID);ci.Calendar.TwoDigitYearMax=2099;//使用我们的自定义区域性解析日期。DateTimedt=DateTime.ParseExact(输入,"MMM-yy",ci);returnnew{Month=dt.ToString("MMMM"),Year=dt.ToString("yyyy")};这是我的准日期字符串列表Listdates=newList(new[]{"May-10","Jun-30","Jul-10","Apr-08","Mar-07"});像这样扫描它:foreach(objectobjindates.Select(d=>ConvertCustomDate(d))){Console.WriteLine(obj);注意,它现在将30处理为2030而不是1930...您正在寻找Calendar.TwoDigitYearMax属性。JonSkeet发布了一些您可能会觉得有用的东西。我有一个类似的问题,我用正则表达式解决了它。你的情况是这样的:以上就是C#学习教程的全部内容:DateTime.TryParseCenturyControlC#,如果对大家有用,需要进一步了解C#学习教程,希望大家多多付出注意—privatestaticreadonlyRegexDateRegex=newRegex(@"^[0-9][0-9](Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[0-9][0-9]$",RegexOptions.Compiled|RegexOptions.ExplicitCapture);privatestaticstringBeautify(stringdate){varmatch=DateRegex.Match(date);if(match.Success){//可能进一步检查返回日期是否正确date.Insert("dd-MMM-".Length,"20");}归期;}结果=year.ToString().Length==1||year.ToString().Length==2?"1":(Convert.ToInt32(year.ToString().Substring(0,(year.ToString().Length-2)))+1).ToString();本文收集自网络,不代表任何内容,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处: