Using Timespan...

  • Thread starter Thread starter Beringer
  • Start date Start date
B

Beringer

I would like an exact way to calculate the number of years, months and days
from the TimeSpan.Days property.
Can anybody help me?

Thanks in advance,
Eric
 
These are all seperate properties within the TimeSpan structure

A TimeSpan object does not have the ability to return anything bigger
than the number of days. One could argue that it could do weeks as well,
but it doesn't, but that's easy to calculate.

On the matter of months and above, the subject becomes trickier.

If a TimeSpan object has a value of 2592000 seconds, which equtes to 30
days, how many months is this ? 0 ? 1 ? It depends on the month of
course.

The same goes for years because of the leap year issue.

This means that the best you'll get is an estimate based on some
assumptions, like "every month is 30 days", in which case you can just
divide the Days property by 30.

If you need a specific value, you need the starting point too, so that
you can calculate the right values according to actual months and years.
 
Beringer said:
I would like an exact way to calculate the number of years, months and days
from the TimeSpan.Days property.
Can anybody help me?

You have a few options, including:

1) use VB.NET's DateDiff function

2) roll your own using support from the Calendar class

Note that in both cases you'll need more than a TimeSpan object - you'll
need a DateTime object so the calculation can have a point of reference.
Once you have that reference point, if you need another DateTime
object (for the DateDiff function, for example), you can get it by
simply adding the TimeSpan to the DateTime you have.
 
Back
Top