How can I specify the latest time of day with DateTime

后端 未结 12 1073
不思量自难忘°
不思量自难忘° 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:48
    DateTime d = DateTime.Today.AddDays(1).AddTicks(-1);
    
    0 讨论(0)
  • 2020-12-14 14:48

    Using an Extension Method

    public static DateTime EndOfTheDay(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, date.Day).AddDays(1).AddTicks(-1);
    }
    

    The result here would provide you with the latest time possible by getting the beginning of the day - add a day and then subtract one tick. Other methods add Hours, Minutes and Seconds however those solutions depending on code functions will cause issues for any time between 23:59:59.000000 and 23:59:59.999999

    For example if I want to know if a value is before a certain end date / time , the possibility with other solutions is that they would miss values in the millisecond range.

    0 讨论(0)
  • 2020-12-14 14:49

    Why not ToDayEnd() extension

    /// <summary>
        /// Gets the value of the End of the day (23:59)
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static DateTime ToDayEnd(this DateTime target)
        {
            return target.Date.AddDays(1).AddMilliseconds(-1);
        }
    

    But if you would really mean the absolute end of the day then AddTicks(-1) is the answer.

    0 讨论(0)
  • 2020-12-14 14:49

    this will give you the expected result:

    DateTime startDate= DateTime.Now.Date;
    DateTime endDate= startDate.AddDays(2).Add(new TimeSpan(23, 59, 59));
    //startDate: 28/9/2017 0:0:0 endDate: 29/9/2017 23:59:59
    
    0 讨论(0)
  • 2020-12-14 14:53
    DateTime startDate = DateTime.Today;
    DateTime stopDate = startDate.AddDays(1).AddTicks(-1);
    

    As a note, DateTime.Today returns (from MSDN)

    A System.DateTime set to today's date, with the time component set to 00:00:00.

    So as others have noted, add a day, then subtract the smallest time quantum (a tick), and you get the last possible time for the current day.

    Of course, you might have to think about TimeZones and such depending where the code runs versus where the user is. UTC time might be good, but that might bump you off a day (either way) depending where your code runs.

    0 讨论(0)
  • 2020-12-14 14:54

    For example

    DateTime.Now.Date.AddDays(1).AddSeconds(-1)
    

    Or AddTicks/AddMilliseconds/AddMinutes... based on the precision you need.

    0 讨论(0)
提交回复
热议问题