Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increment a date?

Tags:

c#

.net

I have two dates as duedate as 03/03/2011 and returndate as 03/09/2011. I want to find the fine in double when I subtract duedate from returndate.How can duedate be incremented?

like image 742
Siva Avatar asked Mar 03 '11 06:03

Siva


People also ask

How can I increase my date in 7 days?

To increment a date by 7 days: Use the getDate() method to get the day of the month of the specific date. Use the setDate() method to increment the date by 7 days. The setDate method takes the day of the month as a parameter and sets the value for the date.

How do I increase day by 1 in Excel?

Enter your due dates in column A. Enter the number of days to add or subtract in column B. You can enter a negative number to subtract days from your start date, and a positive number to add to your date. In cell C2, enter =A2+B2, and copy down as needed.


2 Answers

The logical solution would seem to be the AddDays method, as in the other answers.

However, I try (in general) never to use floating point (i.e. a double) when working with monetary or date values.

DateTime contains a time component and AddDays takes a double as argument (fractional part becomes time), so I tend to avoid use of that method.

Instead, I use

dueDatePlusOne = dueDate.AddTicks(TimeSpan.TicksPerDay);

This should result in slightly faster execution too. Not that it still matters much on today's hardware, but I started out coding for microprocessors with a <1 MHz clock speed and old PDP-8's and -11's and stuff like that back in the 1970's, and some habits never die ;)

like image 73
Luc VdV Avatar answered Oct 11 '22 17:10

Luc VdV


Following code might help you:

var dueDate = new DateTime(2011, 3, 3);

//if you want to increment six days
var dueDatePlus6Days = dueDate.AddDays(6);

//if you want to increment six months
var dueDatePlus6Months = dueDate.AddMonths(6);

var daysDiff1 = (dueDatePlus6Days - dueDate).TotalDays; //gives 6
var daysDiff2 = (dueDatePlus6Months - dueDate).TotalDays; //gives 184
like image 21
Hemant Avatar answered Oct 11 '22 15:10

Hemant