【问题标题】:Map format YY.MM date time to MM.YYYY date time将格式 YY.MM 日期时间映射到 MM.YYYY 日期时间
【发布时间】:2019-08-30 10:23:52
【问题描述】:

在数据库中,我有一个字符串表示日期时间,格式为 YY.MMYY 表示 YearMM 表示 Month。例如21.03 = 2021.03)

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

【问题讨论】:

  • 你尝试了什么?如果它是一个字符串,听起来应该非常简单..
  • 如果您没有特殊原因,请不要将您的DateTime 值作为string 保存在您的数据库中。这是一个坏习惯。 sqlblog.com/blogs/aaron_bertrand/archive/2009/10/12/… 另一方面,你的问题根本不清楚。你能读几遍How to Ask吗?如果您要求在 C# 端将其解析为 DateTime,您可以使用 yyyy.MM 格式和具有适当文化的 ParseExactTryParseExact 方法。还要注意区分大小写的问题。 MM 是几个月,mm 是几分钟。
  • 这个数据库不是我自己的!我不允许编辑它!
  • 19.12 是 2019.12 还是 1912.12 怎么识别?
  • @SanuAntony:你可以假设只有 2019 年是正确的。

标签: c# datetime converters


【解决方案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");

【讨论】:

  • 谢谢!以及如何根据格式类型比较两个日期时间?例如,如果我有“MM.YYYY”,我不想解析日期时间。
  • @Jahan:在使用 date 时,请使用为此专门设计DateTime 类:Parse[Exact] 只是其中之一行,然后您可以放置​​一个易于阅读的if ((date1 == date2) && (date2 < date3)) {...},而不需要复杂且容易出错的string 操作。从 RDBMS 读取string,将其解析为DateTime,执行所有业务逻辑,最后,如果需要,将其格式化回String
  • 为描述.Calendar.TwoDigitYearMax而投票。
【解决方案2】:

您可以使用字符串拆分功能这样做:

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"

【讨论】:

  • Microsoft 对 1900/2000 模糊性的标准似乎要在 29/30 年取消。 support.office.com/en-ie/article/…。但是如果数据库只包含过去的日期,你的算法就很好。
  • 无论如何,它很快就会改变(就像我们在 2019 年一样)。从 Win 7 开始,您可以在区域设置中进行更改。
猜你喜欢
  • 2011-08-12
  • 2014-06-08
  • 1970-01-01
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多