How can I specify the latest time of day with DateTime

后端 未结 12 1074
不思量自难忘°
不思量自难忘° 2020-12-14 14:03

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

相关标签:
12条回答
  • 2020-12-14 14:58

    yourDateInstance.CloseDate = yourDateInstance.CloseDate.Date.AddDays(1).AddMilliseconds(-1);

    0 讨论(0)
  • 2020-12-14 15:04

    use this

    DateTime YourNewDate = new DateTime(YourDate .Year, YourDate .Month, YourDate .Day, 23, 59, 59, 99);

    0 讨论(0)
  • 2020-12-14 15:06

    If you already have a DateTime object created and want to replace the time with the 11:59:59PM for that given date, then you can use the .Date property to get the date with time set to 00:00:00 and then add the hours, minutes and seconds. For example:

    var dt = yourDateInstance.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
    

    If by latest time, you mean 11:59:59 PM, then this should also work:

    var dt = new DateTime(Now.Year, Now.Month, Now.Day, 23, 59, 59);
    
    0 讨论(0)
  • 2020-12-14 15:08

    Your question has already been answered, but IMHO a better way is not to bother attempting to subtract a tick, a second, or whatever from the end of the range, and compare using strictly less than.

    So that if you want all dates in an inclusive range from startDate to endDate, ignoring the time, you could use the following in C#:

    if ((myDate >= startDate.Date) && (myDate < endDate.Date.AddDays(1)))
    {
        // ... it's in the range
    }
    

    or in T-SQL, assuming your @StartDate and @EndDate are exactly midnight, something like:

    WHERE SomeDate >= @StartDate AND SomeDate < DATEADD(d,1,@EndDate)
    

    UPDATE

    Updated example to show an inclusive range in response to comments.

    0 讨论(0)
  • 2020-12-14 15:08

    Based on the other answers I created this convenient extension method:

    public static class DateTimeExtensions
    {
        public static DateTime EndOfDay(this DateTime dateTime)
        {
            return dateTime.Date.AddDays(1).AddTicks(-1);
        }
    }
    
    0 讨论(0)
  • 2020-12-14 15:09

    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
    
    0 讨论(0)
提交回复
热议问题