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

时间:2019-04-09 07:42:07

标签: c# datetime converters

在数据库中,我有一个表示日期时间的字符串,其格式为YY.MMYY表示 Year ,而MM Month < / em>。例如21.03 = 2021.03

如何使用数据注释或其他方式将此特殊的format(yy.mm)映射到此format(mm/yyyy)

2 个答案:

答案 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..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");

答案 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"