Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set time to midnight for current day?

Tags:

c#

.net

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?

like image 650
genxgeek Avatar asked Nov 20 '12 05:11

genxgeek


3 Answers

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);
like image 185
Chris Moutray Avatar answered Oct 24 '22 02:10

Chris Moutray


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;
like image 37
Justin Pihony Avatar answered Oct 24 '22 03:10

Justin Pihony


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));
like image 8
Ravi Ram Avatar answered Oct 24 '22 03:10

Ravi Ram