地图格式YY.MM日期时间为MM.YYYY日期时间

问题描述 投票:-1回答:2

在数据库中,我有一个字符串,表示格式为YY.MM的日期时间(YY表示年份和MM是月份。例如21.03 = 2021.03

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

c# datetime converters
2个回答
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如果你想改变你可以创建的这个策略并使用你自己的文化:

  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");

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"
© www.soinside.com 2019 - 2024. All rights reserved.