Whether the right approach, or you can do the job with the date easier. In particular, it is necessary to select a sample of fields from the database, the date of which is between the beginning and the end of the current day, that is, from 00:00:00 to 00:00:00 of the new day. Since it is planned to use in different time zones, I use UTC.

This is how I declare the sampling range

var startOfDay = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0); var endOfDay = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.AddDays(1).Day, 0, 0, 0); 

Then, I make a query to the database, where I check whether the date of the record belongs to the specified range. In the database, the date is stored in UTC format.

  • It all depends on the context. It is probably easier to write to the store (with all the logic) and just pull it from C #. - free_ze

2 answers 2

No, wrong.

  1. The date may change between appeals to DateTime.UtcNow , so you may get an incorrect date (with an error of a day, month, or year).

  2. Still easier:

     var startOfDay = DateTime.UtcNow.Date; var endOfDay = startOfDay.AddDays(1); 

    First, this code does not work correctly on the last day of the month: you change the day, but not the month.

    Secondly, it can be easier:

     var startOfDay = DateTime.UtcNow.Date; var endOfDay = startOfDay.AddDays(1); 
    • Oh, we almost equally answered, only you found another bug :) - Qwertiy
    • @Qwertiy: Yeah, and both were fixed :) - VladD
    • And which of the two of me should I mention correctly? :))) - QuaternioNoir
    • @QuaternioNoir, who found a more interesting bug?) - Qwertiy
    • @QuaternioNoir: As a last resort , toss a coin :) - VladD