FarFigNewton
FarFigNewton

Reputation: 7273

Get today's date at midnight or no minutes and seconds

How can I get the current date but at midnight in a date object instead of a string object?

I know I can do this Date.Now.ToShortDateString, but that returns a string object. But if I do this Convert.ToDateTime(Date.Now.ToShortDateString), it seems like too much code. Let me know if I should just get over this and use it.

Reason, I need to compare two dates and the date I'm comparing it to only has a date and no time.

Upvotes: 4

Views: 1592

Answers (3)

jason
jason

Reputation: 241641

Just use the Date property on DateTime to get the Date with the time set to midnight for a given instance of DateTime.

// dateTime is an instance of DateTime
var date = dateTime.Date;

And more specifically, you can say

var today = DateTime.Today;

to get the current date at midnight (this is the same as saying)

var today = DateTime.Now.Date;

Upvotes: 2

SWeko
SWeko

Reputation: 30902

There is a DateTime.Today field specifically for that purpose.
You can also use DateTime.Date property to get just the date of any datetime object, so DateTime.Now.Date will also work.

Upvotes: 6

Jim Mischel
Jim Mischel

Reputation: 134005

Look at the Date property:

DateTime.Now.Date

Upvotes: 6

Related Questions