在数据库中,我有一个表示日期时间的字符串,其格式为YY.MM
(YY
表示 Year ,而MM
是 Month < / em>。例如21.03 = 2021.03
)
如何使用数据注释或其他方式将此特殊的format(yy.mm)
映射到此format(mm/yyyy)
?
答案 0 :(得分:1)
尝试输入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
,如果您想更改此策略,则可以创建并使用自己的 culture :
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");
答案 1 :(得分:0)
您可以使用字符串拆分功能来做到这一点:
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"