Home > Net >  Finding out if specific date is somewhere between two other dates for any year in C#
Finding out if specific date is somewhere between two other dates for any year in C#

Time:11-29

So I'm making pretty simple console app for applying a discount for your flight depending on your case. In one case I can't add a discount if flight date is somewhere between YYYY/12/20 – YYYY( 1)/01/10 and between YYYY/03/20 – YYYY/04/10 but I'm not really sure how to approach that. I thought about specifying it like this:

DateTime springSeasonStart = new DateTime(DateTime.Now.Year, 03, 20);
DateTime springSeasonEnd = new DateTime(DateTime.Now.Year, 04, 10);

and then check if my flightDate is somewhere between springSeasonStart and springSeasonEnd. If it is, the discount wouldn't apply but it doesn't really work because year can't be specified, only month and day can. So what can I do to achieve what I need?

CodePudding user response:

Check if the start month is greater than end month. If it's greater, than it's next year and you need to add 1 year for the end date.

var date = new DateTime(2021, 12, 25); // flight date

// season start
var monthStart = 12;
var dayStart = 20;

// season end
var monthEnd = 1;
var dayEnd = 10;

var yearEndModifier = monthStart > monthEnd ? 1 : 0; //  1 if next year

var SeasonStart = new DateTime(date.Year, monthStart, dayStart);
var SeasonEnd = new DateTime(date.Year   yearEndModifier, monthEnd, dayEnd);

if (date >= SeasonStart && date <= SeasonEnd)
    Console.WriteLine("Discount");
else
    Console.WriteLine("No Discount");

In second case YYYY/03/20 – YYYY/04/10, yearEndModifier = 0 because start month is lesser than end month.

  • Related