映射格式 YY.MM 日期时间到 MM.YYYY 日期时间

Map format YY.MM date time to MM.YYYY date time

在数据库中,我有一个表示日期时间的字符串,格式为 YY.MMYY 表示 Year 并且 MM月份。例如21.03 = 2021.03)

如何使用数据注释或其他方式将此特殊 format(yy.mm) 映射到此 format(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"

尝试 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..292000..202930..991930..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");