.netdatetime

How can I specify the latest time of day with DateTime


I am using a System.DateTime object to allow a user to select a date range. The user is only able to select a date (not time) using a third party calendar so I will need to automatically specify the time of day it should use (ie: 00:00:00 or 23:59:59) after the date is chosen.

How can I specify the time after the date is already stored as a DateTime object by the calendar selector? I could use the AddHours, AddMinutes, AddSeconds methods but those are relative to the current time which may not be 00:00:00.

The startDate will need to have a time of 00:00:00 and endDate have a time of 23:59:59 to account for the entire days.


Solution

  • To get the last instant for today:

    DateTime d = new DateTime(Now.Year, Now.Month, Now.Day);
    d = d.AddDays(1);
    d = d.AddTicks(-1);
    

    In response to your edit, here's what I would do:

    DateTime start = new DateTime(Now.Year, Now.Month, Now.Day);
    DateTime end = start.AddDays(1).AddTicks(-1);
    
    // Or - just use end = start.AddDays(1), and use a < for comparison