-2

I have this short block of code that is checking a DateTime variable.

It looks like this:

DateTime launchDay = DateTime.Today;
// launchTime.Begin is a DateTime? type
if (launchTime.Begin == null || launchTime.Begin > launchDay) return NoContent();

The problem is, launchDay is 'today', which is apparently midnight?

So if my launchTime.Begin is, let's say 2pm....then that is greater(after) 'launchDay' because 'launchDay' is set at 12AM.

How can I compare the dates so that I know that they are on the same day and not worry about the time so much?

I only want it to return NoConent() if launchTime.Begin is null or launchTime.Begin is not on the same day as the launchDay.

Is there a way to do this without running into the issue I am coming up against?

Thanks!

SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185

1 Answers1

2

The DateTime type consists of two components: The date component and the time component. When you only care about the date (but not the time), then the time component is usually set to the default which is 0:00:00 (i.e. midnight).

This is also explained on DateTime.Today:

An object that is set to today's date, with the time component set to 00:00:00.

In order to work with dates, ignoring the time components, you can use the Date property which will basically copy your DateTime value while settings the time component to midnight.

This allows you to do such comparisons:

if (launchTime.Begin == null || launchTime.Begin.Date > DateTime.Today)
    return NoContent();
poke
  • 369,085
  • 72
  • 557
  • 602
  • Thanks! I played around with Parse and ParseExact as another question answer I found but that didn't help. So basically, I can do this? launchTime.Begin.Value.Date > launchDay.Date? – SkyeBoniwell Aug 03 '20 at 14:09
  • 1
    @SkyeBoniwell Yeah, that should work. Note that if `launchDate` is `DateTime.Today`, then it already has no time component. So accessing `Date` of it doesn’t change anything. – poke Aug 03 '20 at 14:50