views:

610

answers:

3

Near duplicates

How do I calculate relative time?

How do I calculate someone’s age in C#?

Anyone know how of a function in VB.NET or C# that will take two dates, calculate the difference and output that difference in an english string? For example if I pass the dates '3/10/2009' and '3/25/2009', the function would return the string "15 Days" or if I pass the dates '3/10/2005' and '3/15/2007', the function would return "2 Years, 5 days"

+3  A: 

Use the DateDiff function in VB.NET

Here's some code that will give you years, months and days:

    Dim Date1 = Date.Parse("1/10/2008")
    Dim Date2 = Date.Parse("3/25/2009")
    Dim Years = DateDiff(DateInterval.Year, Date1, Date2)
    If Years > 0 Then
        Date1 = Date1.AddYears(Years)
    End If
    Dim Months = DateDiff(DateInterval.Month, Date1, Date2)
    If Months > 0 Then
        Date1 = Date1.AddMonths(Months)
    End If
    Dim Days = DateDiff(DateInterval.Day, Date1, Date2)
    Console.WriteLine("{0} years, {1} months, {2} days", Years, Months, Days)

Output: 1 years, 2 months, 15 days

You could add a bit more logic to conditionally show each span only if it's not zero and also to use year or years, month or months and day or days, but this code should get you headed in the right direction.

Dennis Palmer
Now this is what I'm looking for! Thank you Dennis
Alan
@Alan, perhaps you might consider accepting Dennis' answer.
Adam Bernier
A: 

offtopic but related: If you want to do it the other way around, that is to parse "tomorrow" into Today+1 you can use this: http://www.codeplex.com/DateTimeEnglishParse

zvolkov
A: 

DateDiff can get you the correct data (difference between 2 dates).

But what is the correct English output? The parameters for this function will be complex:

Pub Function dateToEnglish(ByVal culture as Culture.Info, ByVal personality as Personality, ByVal mood as Mood ....)

For example, what should be the correct answer for "14 days"

"A coupla weeks" "Two weeks" "14 days" "about half a month" "bi-weekly"

Larry Watanabe
A fortnight! :)
Matt Hamilton