在英语中的时间差时间差、英语

2023-09-03 04:23:07 作者:独守、阴晴圆缺

我如何计算相对时间?

如何计算一个人的年龄在C#中?

任何人都知道如何在VB.NET的函数或C#,将采取两个日期,计算英文字符串的差异,输出的区别?例如,如果我传递的日期2009年3月10日和2009年3月25日,该函数将返回字符串15天,或者如果我通过日期'3/10/2005'和'3 / 15/2007号,该函数将返回2年,5天

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"

推荐答案

使用则DateDiff 在VB.NET功能

Use the DateDiff function in VB.NET

下面是一些code,这将使你年,月,日:

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)

输出: 1年2个月,15天

Output: 1 years, 2 months, 15 days

您可以添加更多的逻辑来有条件地显示每个跨度只有当它不为零,并用一年或数年,月或数月,日或数天,但这code应该让你在正确的方向前进

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.