Every time that I create a non-nullable datetime in my mvc3 application it defaults to now(), where now is current date with current time. I would like to default it to today's date with 12am as the time.
I'm trying to default the time in my mvc...but...the following isn't setting to todays date @12am. Instead it defaults to now with current date and time.
private DateTime _Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 0, 0);
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
How can I set to 12am for the current date for non-nullable datetime?
You can use the Date
property of the DateTime object - eg
DateTime midnight = DateTime.Now.Date;
So your code example becomes
private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...
var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
I believe you are looking for DateTime.Today
. The documentation states:
An object that is set to today's date, with the time component set to 00:00:00.
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
Your code would be
DateTime _Begin = DateTime.Today;
Using some of the above recommendations, the following function and code is working for search a date range:
Set date with the time component set to 00:00:00
public static DateTime GetDateZeroTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
Usage
var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);
var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With