gpt4 book ai didi

c# - 如何比较月年与 DateParse

转载 作者:太空狗 更新时间:2023-10-29 20:01:47 25 4
gpt4 key购买 nike

我必须检查日期(月-年)是否小于实际日期。

我知道如何只用一个月或一年来做,比如

DateTime.Parse(o.MyDate).Month <= DateTime.Now.Month

DateTime.Parse(o.MyDate).Year <= DateTime.Now.Year

但是我如何直接检查 month-year 是否小于 now.month-now.year?

编辑

例如,我要做的是检查 10-2011 (DateTime.Now.Month-DateTime.Now.Year) 是否在 01-2011 和 04-2012 之间...

最佳答案

如果年份相同,比较月份,如果年份不同,你的年份一定比现在小:

var yourDate = ...;
if((yourDate.Year == DateTime.Now.Year && yourDate.Month < DateTime.Now.Month)
|| yourDate.Year < DateTime.Now.Year)
{
// yourDate is smaller than todays month.
}

更新:

要检查 yourDate 是否在特定时间范围内,请使用:

var yourDate = ...;
var lowerBoundYear = 2011;
var lowerBoundMonth = 1;
var upperBoundYear = 2012;
var upperBoundMonth = 4;

if(((yourDate.Year == lowerBoundYear && yourDate.Month >= lowerBoundMonth) ||
yourDate.Year > lowerBoundYear
) &&
((yourDate.Year == upperBoundYear && yourDate.Month <= upperBoundMonth) ||
yourDate.Year < lowerBoundYear
))
{
// yourDate is in the time range 01/01/2011 - 30/04/2012
// if you want yourDate to be in the range 01/02/2011 - 30/04/2012, i.e.
// exclusive lower bound, change the >= to >.
// if you want yourDate to be in the range 01/01/2011 - 31/03/2012, i.e.
// exclusive upper bound, change the <= to <.
}

关于c# - 如何比较月年与 DateParse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7873596/

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