在数据库中,我有一个字符串,表示格式为YY.MM
的日期时间(YY
表示年份和MM
是月份。例如21.03 = 2021.03
)
如何使用数据注释或其他方式将此特殊format(yy.mm)
映射到此format(mm/yyyy)
?
尝试Parse
日期,然后格式化回string
:
using System.Globalization;
...
string source = "21.03";
// 03.2021
string result = DateTime
.ParseExact(source, "yy'.'MM", CultureInfo.InvariantCulture)
.ToString("MM'.'yyyy");
但是,我们在这里有一个含糊不清的地方:"03.50"
可以是"March 1950"
或"March 2050"
。默认策略是00..29
到2000..2029
和30..99
到1930..1999
如果你想改变你可以创建的这个策略并使用你自己的文化:
CultureInfo myCulture = CultureInfo.InvariantCulture.Clone() as CultureInfo;
// Everything to 20.., never 19..
myCulture.Calendar.TwoDigitYearMax = 2099;
string source = "99.03";
// 03.2099
string result = DateTime.ParseExact(source, "yy'.'MM", myCulture).ToString("MM'.'yyyy");
甚至
CultureInfo myCulture = CultureInfo.CurrentCulture.Clone() as CultureInfo;
// Everything to 20.., never 19..
myCulture.Calendar.TwoDigitYearMax = 2099;
// Current culture as usual, except 2 digit year policy
CultureInfo.CurrentCulture = myCulture;
...
string source = "99.03";
// 03.2099
string result = DateTime.ParseExact(source, "yy'.'MM", null).ToString("MM'.'yyyy");
您可以使用字符串拆分功能这样做:
string dateIn = "11.10";
string month = dateIn.Split('.')[1]; //split the String at the point and save it
string year = dateIn.Split('.')[0];
string dateOut = $"{month}/20{year}"; //build a new string
//this will fix the 1900/2000 issue more or less as all dates in the furutre would be send back to the past you can adapt this to your need:
if( DateTime.Now.Year < Convert.ToInt32($"20{year}"))
{
dateOut = $"{month}/19{year}";
}
//dateOut is "10/2011"