Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Now.AddDays(-1) will get date-time for exactly 24hrs ago, but how do I get the time for yesterday at a specific hour?

I want to somehow specify a time in my Datetime.Now so for instance I know that

DateTime.Now.AddDays(-1);

will get the date for yesterday exactly 24hrs ago but I want to get the date for yesterday at a specific time, for instance 5pm.

I can't find anything useful in relation to this on StackOverflow, any suggestions?

like image 219
user3668266 Avatar asked Jun 16 '14 10:06

user3668266


2 Answers

Use:

DateTime.Now.Date.AddDays(-1).AddHours(17);
like image 117
chaliasos Avatar answered Sep 18 '22 12:09

chaliasos


You can create an instance of TimeSpan and delete/add in DateTime.Now.

OR

DateTime dt = DateTime.Now.AddDays(-1);

DateTime newdt = New DateTime(dt.Year, dt.Month, dt.Day, 17, 0, 0);
like image 37
Nikhil Agrawal Avatar answered Sep 21 '22 12:09

Nikhil Agrawal