如何将“MM/dd/yy”字符串转换为最近一年的日期?
c#
我将日期作为字符串输入,格式为MM/dd/yy.
我正在尝试将其转换为DateTimeOffset以下方式:
string dateString = "02/11/48";
DateTimeOffset.TryParseExact(
dateString,
"MM/dd/yy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTimeOffset date);
然而,当这个字符串被转换为 时DateTimeOffset,年份被设置为 1948。由于业务逻辑,我知道那里的日期总是有最近的未来年份,所以年份应该是 2048。
有没有办法将字符串转换为DateTimeOffset这种方式,或者在解析后我是否必须在其上添加额外的逻辑?
回答
您可以使用这种更简单的方法:
string dateString = "02/11/48";
DateTimeOffset.TryParseExact(
dateString,
"MM/dd/yy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTimeOffset date);
if (date < DateTimeOffset.UtcNow)
{
date = date.AddYears(100);
}
如果解析的值在现在之前,它只会增加 100 年。
- There is just this one small problem with February 29th. In 99.5% of cases, two years a century apart will either both be leap years or neither will be. But for example 2000 was a leap year and 2100 will not be.