将“MM/yy”转换为日期时间 C#

问题描述

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

但是当我从数据库中检索它时,我需要将其转换为 DateTime 值。是否有任何正确的方法可以做到这一点?

解决方法

试试这个。将此行 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);
,
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 运算符 < 可能更有效,在这种情况下,您可以添加一个月但减去打勾。