How to get datetime yesterday and tomorrow in C #

I have a code:

int MonthNow = System.DateTime.Now.Month; int YearNow = System.DateTime.Now.Year; int DayNow = System.DateTime.Now.Day; 

How can I get day, month and year in C # yesterday and tomorrow?

Of course, I can just write:

 DayTommorow = DayNow +1; 

but it may happen that tomorrow is another month or year. Are there any built-in tools in C # to learn yesterday and today?

+55
c # datetime
Nov 20 '11 at 19:04
source share
7 answers

You can find this information directly in the API link .

 var today = DateTime.Now; var tomorrow = today.AddDays(1); var yesterday = today.AddDays(-1); 
+46
Nov 20 '11 at 19:08
source share
 DateTime tomorrow = DateTime.Now.AddDays(1); DateTime yesterday = DateTime.Now.AddDays(-1); 
+143
Nov 20 2018-11-11T00:
source share

Today:

DateTime.Today

Tomorrow:

 DateTime.Now.AddDays(1) 

Yesterday:

 DateTime.Now.AddDays(-1) 
+14
Nov 20 '11 at 19:07
source share

You want DateTime.Today.AddDays(1) .

+12
Nov 20 '11 at 19:05
source share

Use DateTime.AddDays() ( MSDN Documentation DateTime.AddDays Method ).

 DateTime tomorrow = DateTime.Now.AddDays(1); DateTime yesterday = DateTime.Now.AddDays(-1); 
+10
Nov 20 2018-11-11T00:
source share

You should do it this way if you want to receive yesterday and tomorrow at 00:00:00:

 DateTime yesterday = DateTime.Today.AddDays(-1); DateTime tomorrow = DateTime.Today.AddDays(1); // Output example: 6. 02. 2016 00:00:00 

Just remember that if you do it like this:

 DateTime yesterday = DateTime.Now.AddDays(-1); DateTime tomorrow = DateTime.Now.AddDays(1); // Output example: 6. 02. 2016 18:09:23 

then you will get the current time minus one day, not yesterday at 00:00:00.

+10
Feb 05 '16 at 17:10
source share

The trick is to use "DateTime" to manage dates; use integers and strings when you need a โ€œfinal resultโ€ from a date.

For example (pseudo code):

  • Get "DateTime Tomorrow = Now + 1"

  • Determine the date, day of the week, day of the month - no matter what you want - the total date.

+2
Nov 20 2018-11-11T00:
source share



All Articles