Nate Pet
Nate Pet

Reputation: 46222

Assign datetime value to today's date with specific time

I have a variable which is defined as a DateTime. I need to assign it today's date but have the time be 4 PM. How do I do this?

Upvotes: 24

Views: 39904

Answers (4)

musefan
musefan

Reputation: 48415

I think this should do what you need...

DateTime today = DateTime.Today;
DateTime dt = new DateTime(today.Year, today.Month, today.Day, 16, 0, 0);

Upvotes: 19

Grant Winney
Grant Winney

Reputation: 66449

Take a look at all the overloaded constructors for DateTime.

DateTime myDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 16, 0, 0);

Edit: Correction. Thanks Jon. :)

Upvotes: 2

Anders Marzi Tornblad
Anders Marzi Tornblad

Reputation: 19305

var anotherTime = DateTime.Today.AddHours(16.0);

Upvotes: 4

SLaks
SLaks

Reputation: 887459

You want DateTime.Today.AddHours(16)

DateTime.Today will return today's date at midnight.
You can also use the Date property to drop the time from an arbitrary DateTime value.

Upvotes: 43

Related Questions