sam13142
sam13142

Reputation: 15

How do i pass just a the date (no time) into a method taking a DateTime Variable?

I want to pass just the date not time into a parameter. I have tried DateTime.Now.Date but this just sets the time to midnight. Any Ideas?? Here is my code:

GetAppointmentsOnSelectedDate(DateTime.Now);

Upvotes: 0

Views: 1528

Answers (3)

uncoder
uncoder

Reputation: 1876

The DateTime structure does what it says - it stores a date along with time. If you need just the date portion, use the Date member property and simply ignore the time portion. Such an approach should work 99% of the time. The only caveat is serialization and deserialization in different time zones, which can cause your DateTime value to shift.

Alternatively, it should not be too hard to create your own Date structure.

Upvotes: 0

mason
mason

Reputation: 32704

The DateTime object has a Date property which returns a DateTime set to midnight of the parent object. If you change your code to this:

GetAppointmentsOnSelectedDate(DateTime.Now.Date);

and modify GetAppointmentsOnSelectedDate to only care about the Date component of the object it receives, that should do what you want. Of course, when converting to a string and displaying it in the UI you'll want to leave off the time component.

Strictly speaking, using the .Date property isn't necessary if GetAppointmentsOnSelectedDate doesn't look at the time component anyways.

Upvotes: 3

rory.ap
rory.ap

Reputation: 35318

A DateTime is a data type; you cannot manipulate what it parts of the data it inherently "shows". If you're looking to display it, you need to convert it to a string, e.g. via DateTime.Now.ToShortDateString().

Upvotes: 0

Related Questions