Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change DateTime to Midnight

Tags:

c#

datetime

I have the following EffectiveDay which I want to change datetime to the midnight.

public DateTime EffectiveDate { get; set; }

enter image description here

In the screenshot, it shows 02/28/2018 5:00:00 AM.

I want to change it to 02/28/2018 12:00:00 AM (midnight)

I tried the following approach, it did not work

ClassRoom.WorkOrders.Select(w => w.EffectiveDate).ToList().ForEach(s => s = s.Date);

I tried the following approach as well, it did not work.

ClassRoom.WorkOrders.Select(w => w.EffectiveDate).ToList().ForEach(s => s = GetDateZeroTime(s.Date));

public static DateTime GetDateZeroTime(DateTime date)
{
  return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
like image 960
casillas Avatar asked Mar 22 '26 13:03

casillas


2 Answers

Doing ForEach with assignments after ToList are not going to help, because you are setting s, a parameter that is thrown away after each iteration.

Use a normal foreach loop to do the assignment:

foreach (var w in ClassRoom.WorkOrders) {
    w.EffectiveDate = w.EffectiveDate.Date;
    // w.EffectiveDate = GetDateZeroTime(w.EffectiveDate); would also work
}
like image 181
Sergey Kalinichenko Avatar answered Mar 24 '26 03:03

Sergey Kalinichenko


This should effectively remove the time from all WorkOrders by assigning the EffectiveDate property of each one to a new DateTime object that has no knowledge of any kind of time:

foreach (var workOrder in ClassRoom.WorkOrders)
    workOrder.EffectiveDate = new DateTime(workOrder.EffectiveDate.Year, workOrder.EffectiveDate.Month, workOrder.EffectiveDate.Day, 0, 0, 0);

Setting workOrder.EffectiveDate = workOrder.EffectiveDate.Date in the loop should also work just fine.

like image 42
mm8 Avatar answered Mar 24 '26 04:03

mm8