c# - 将“MM/yy”转换为日期时间c#
问题描述
我正在存储这样的 DateTime 值 - “MM/yy”格式(信用卡信息)02/30
但是当我从数据库中检索它时,我需要将其转换为 DateTime 值。有什么合适的方法吗?
解决方案
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
以上假设您计划使用包含运算符比较结果<=
。
根据您的业务逻辑,使用独占运算符可能更有效<
,在这种情况下,您将添加一个月而不是减去一个刻度。
推荐阅读
- path - 在另一台机器上设置 gdb 源路径
- javascript - Rails 6 - 可排序
- angular - 角度项目中使用的 npm 包的依赖项概述
- php - 试图了解如何制作 UpdateOrCreate
- sql - 如何根据列值选择值?
- php - Mailchimp JSON 使用 PHP foreach 和多个键
- php - 我们需要更改帖子的时间线状态
- html - 在 flexbox 容器中,除了最后一项之外的所有项目都向左对齐
- apache-spark - 多级分区表的 Spark (EMR) 分区修剪行为
- android - 在 android 中首次初始化后,回收器 item_view 的高度正在改变