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.ToSho开发者_Go百科rtDateString
, 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.
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.
Look at the Date
property:
DateTime.Now.Date
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;
精彩评论