gpt4 book ai didi

c# - 如何检查 yyyyMM 格式的有效日期

转载 作者:太空狗 更新时间:2023-10-29 23:58:33 25 4
gpt4 key购买 nike

我有一个由我的财务部门运行的内部业务流程。首先,他们以 yyyyMM201009 格式输入日期。我想检查该字符串中的有效日期,但到目前为止我一无所获。

我目前正在探索分解字符串,取前 4 个并检查它们是否在 1990 到 2050 之间(例如),然后取最后 2 个并检查它是否在 01 到 12 之间。

有没有更好的办法?

最佳答案

您可以使用 DateTime.TryParseExact查看是否可以正确解析:

bool isValid = false;
DateTime dateValue;
if(DateTime.TryParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateValue))
{
// DateTime parsed, dateValue contains the parsed DateTime

// Can validate dateValue against business rules at this point
isValid = (dateValue <= DateTime.Now && dateValue >= DateTime.Now.AddYears(-5));
}

如果你更愿意得到一个异常(exception),你可以使用DateTime.ParseExact :

// Next line throws exception if format not correct
DateTime.ParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture);

关于c# - 如何检查 yyyyMM 格式的有效日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3618104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com