How to get the start and end times of a day

后端 未结 10 698
无人及你
无人及你 2020-12-24 00:29

In my C# app, I pass a string variable that is of format yyyymmdd-yyyymmdd that represents a from and to date. I want to get the start and end times for these dates respecti

相关标签:
10条回答
  • 2020-12-24 01:13

    For SQL Server (version 2008 R2 tested) this ranges works.

    StarDate '2016-01-11 00:00:01.990' EndDate '2016-01-19 23:59:59.990'

    Seems like ticks is greater that the last second of day and automatically round to next day. So i test and works, i made a dummy table with two dates for check what values is sql server catching and inserting in the stored procedure those parameters.

    0 讨论(0)
  • 2020-12-24 01:14

    I am surprised to see how an incorrect answer received so many upvotes:

    Wrong value

    The correct version would be as follows:

    public static DateTime StartOfDay(this DateTime theDate)
    {
        return theDate.Date;
    }
    
    public static DateTime EndOfDay(this DateTime theDate)
    {
        return theDate.Date.AddDays(1).AddTicks(-1);
    }
    
    0 讨论(0)
  • 2020-12-24 01:15

    If you are only worried about .Net precision...

    startDate = DateTime.ParseExact(dates[0], "yyyyMMdd");
    endDate = DateTime.ParseExact(dates[1], "yyyyMMdd").AddTicks(-1).AddDays(1);
    

    You really don't need to concatenate extra values onto the string for the time portion.


    As an addendum, if you are using this for a query against, for example, a database...

    startDate = DateTime.ParseExact(dates[0], "yyyyMMdd");
    endDate = DateTime.ParseExact(dates[1], "yyyyMMdd").AddDays(1);
    

    With a query of...

    WHERE "startDate" >= @startDate AND "endDate" < @endDate
    

    Then the precision issues noted in the comments won't really matter. The endDate in this case would not be part of the range, but the outside boundary.

    0 讨论(0)
  • 2020-12-24 01:17

    I think we're doing it wrong. There is no such thing as the end of the day. AddTick(-1) only works under the convention that there are no time intervals smaller than a tick. Which is implementation dependent. Admittedly the question comes with a reference implementation, namely the .Net Framework DateTime class, but still we should take this as a clue that the function we really want is not EndOfDay() but StartOfNextDay()

    public static DateTime StartOfNextDay(this DateTime date)
    {
        return date.Date.AddDays(1);
    }
    
    0 讨论(0)
提交回复
热议问题