Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a DateTime to 23:59:59 [duplicate]

Tags:

c#

datetime

can someone explain me why do this :

        public virtual ActionResult RecupererVehicules([DataSourceRequest] DataSourceRequest request, String dateMin, String dateMax)
    {
        // Création des dates
        DateTime min = DateTime.Parse(dateMin);
        DateTime max = DateTime.Parse(dateMax);
        max.AddHours(23).AddMinutes(59).AddSeconds(59);

        return Json(Models.Vehicule.getVehiculesDates(min,max));
    }

Get me this :

dateMin "2016-06-26"
dateMax "2016-07-06"
min {26/06/2016 00:00:00}
max {06/07/2016 00:00:00} <-- Why don't I have 23:59:59 ?

If someone have an answer, I'll be happy to ear it.

like image 922
Axel GALLIOT Avatar asked Aug 24 '26 17:08

Axel GALLIOT


2 Answers

you have to assign the value by

max = max.AddHours(23).AddMinutes(59).AddSeconds(59);

instead of

max.AddHours(23).AddMinutes(59).AddSeconds(59);

otherwise the correct date is being calculated but not assigned.

Alternatively you can also add this timespan by

.AddDays(1).AddSeconds(-1)
like image 54
fubo Avatar answered Aug 26 '26 08:08

fubo


DateTime is an immutable struct. So you cannot change the value of an instance of DateTime. If you add or substract something to a DateTime instance, you get a new instance with the resulting value in return.

So your line

max.AddHours(23).AddMinutes(59).AddSeconds(59);

does not change max, but each Add* call returns a new DateTime. You will need to assign the resulting value to max again:

max = max.AddHours(23).AddMinutes(59).AddSeconds(59);
like image 45
René Vogt Avatar answered Aug 26 '26 08:08

René Vogt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!