MartinChristensen
MartinChristensen

Reputation: 99

Calculation algorithm for Dates

I have previously posted this question. However I was not specific enough, so I am trying to explain it better in this post.

I am currently writing a small program to create invoices. The invoices should be calculated on account of storage time of items e.g. costPerDay * numberOfDaysInStorage.

The invoice is created on a monthly basis, e.g. InvoiceDate = 31/05/2013.

The items start date and end date (in storage) is extracted from a database.

So, I have:

Variables:

 DateTime StartInStorageDate; 
 DateTime EndOfStorageDate;
 DateTime InvoiceDate; //(always last date of month)

Rules

Examples

I hope someone can provide me with some pointers, or some code to help calculate the days. The part I find tricky, is to "look into" a previous month (if one exists) from the invoice date, to check for days.

Thank you.

Upvotes: 2

Views: 786

Answers (2)

Daan
Daan

Reputation: 118

You need to calculate two dates: the start and end of the invoice period:

DateTime invoiceStart = StartInStorageDate.AddDays(5);
DateTime invoiceEnd = InvoiceDate < EndOfStorageDate ? InvoiceDate : EndOfStorageDate; 

double billedDays = Math.Max(0, (invoiceEnd - invoiceStart).TotalDays);

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273844

It requires only a few simple actions:

DateTime endDate = Min(invoiceDate, endOfStorageDate );    // Min() is pseudo code
int daysInStorage = (endDate - StartInStorageDate).Days;
daysInStorage -= 5;
if (daysInStorage < 0) daysInStorage = 0;

Upvotes: 2

Related Questions