【问题标题】:Convert "MM/yy" to datetime c#将“MM/yy”转换为日期时间c#
【发布时间】:2021-02-20 15:29:35
【问题描述】:

我正在像这样存储 DateTime 值 - “MM/yy”格式(信用卡信息)02/30

但是当我从数据库中检索它时,我需要将其转换为 DateTime 值。有什么合适的方法吗?

【问题讨论】:

  • 转化的业务规则是什么?
  • 还有...您上次 PCI 合规审计是什么时候,只是出于好奇?
  • 我知道有人也会问这个问题:)。我不会在我的最后保存它。将这些详细信息保存在 ERP 合作伙伴方面。我要求这个解决方案,因为如果我可以这样做,那么它比更改一堆代码更容易。希望你得到我的 pont?
  • 你先把它存储在date的数据库中吧

标签: c# datetime date-parsing


【解决方案1】:

试试这个。将此行 dateString = "5/01" + "/ 0001"; 替换为 dateString = yourDate.ToString() + "/ 0001"; 。 因为没有年份,所以使用时必须使用月份和日期。

CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;

//Use custom formats with M and MM.
dateString = "5/01" + "/0001";
if (DateTime.TryParseExact(dateString, "M/dd/yyyy", enUS,
                                 DateTimeStyles.None, out dateValue))
   Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);

【讨论】:

  • OP 确实有月份和年份,只是没有日期 - 但仍然可以在那里使用 01
【解决方案2】:
using System;
using System.Globalization;

...


// Your input value
string ccexp = "02/30";

// Clone the invariant culture and give it a new calendar
CultureInfo customCulture = (CultureInfo) CultureInfo.InvariantCulture.Clone();
customCulture.DateTimeFormat.Calendar = (Calendar) customCulture.Calendar.Clone();

// Set the value such that all two-digit years are in the range 2000-2099
customCulture.Calendar.TwoDigitYearMax = 2099;

// Parse the string to a DateTime
DateTime dt = DateTime.ParseExact(ccexp, "MM/yy", customCulture);

// Adjust to very end of month (implied by CC expiration)
dt = dt.AddMonths(1).AddTicks(-1);
        
Console.WriteLine(dt.ToString("o")); //=> 2030-02-28T23:59:59.9999999

Working .NET Fiddle here.

以上假设您计划使用包含运算符<= 比较结果。

根据您的业务逻辑,使用 exclusive 运算符 < 可能更有效,在这种情况下,您将添加一个月但 减去一个刻度.

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 2013-10-25
    • 2020-12-18
    • 1970-01-01
    • 2011-08-16
    • 2013-11-30
    • 1970-01-01
    • 2022-01-25
    • 2012-03-05
    相关资源
    最近更新 更多