Below are a couple of methods for making working with DateTime objects easier that I thought I’d collate into a single post.
Default Value
When using a newly initialised DateTime object as a source for an input field in an MVC project it will default to 01/01/0001. In order to set the default value of a DateTime property on an object you can simply use the following code which was introduced in C# 6.
public DateTime StartDatetime { get; set; } = DateTime.Now;
Start & End of Day
If you want to get the start and end times of a given day then you can use the following extension methods, though rather than using <= end of day it is a better idea to use < start of next day.
public static DateTime StartOfDay(this DateTime theDate)
{
return theDate.Date;
}
public static DateTime EndOfDay(this DateTime theDate)
{
return theDate.Date.AddTicks(-1).AddDays(1);
}
0 Comments