首页 > 解决方案 > 将“MM/yy”转换为日期时间c#

问题描述

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

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

标签: c#datetimedate-parsing

解决方案


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

在这里工作.NET Fiddle。

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

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


推荐阅读