【问题标题】:convert number of days into years,months,days将天数转换为年、月、日
【发布时间】:2015-06-03 06:54:16
【问题描述】:

我需要将天数转换为年、月、日。

示例:根据日期join(DOJ) 和日期Relieve(DOR) 计算员工体验。我们有一个DOJ, DOR and Number 他作为员工工作的天数。

必须计算多少年和多少月和多少天。

Example       : DOJ = 14 Feb 2000
                DOR = 08 aug 2013
Output        : 13 Years - 5 Months - 25 Days

在此先感谢....

【问题讨论】:

  • DOJDORDateTime?
  • 我见过年-日或年-月转换,它们更容易实现。对于年月日,我猜可能会玩时间跨度:p
  • @RyanChu 我已经试过了...没用..感谢您的关注...
  • 如果您已经尝试过 Timespan,请向我们展示您尝试过的内容以及失败的原因。

标签: c# asp.net vb.net datediff days


【解决方案1】:

这对我有用:

var dor = new DateTime(2013, 08, 08);
var doj = new DateTime(2000, 02, 14);

var totalmonths = (dor.Year - doj.Year) * 12 + dor.Month - doj.Month;
totalmonths += dor.Day < doj.Day ? -1 : 0;

var years = totalmonths / 12;
var months = totalmonths % 12;
var days = dor.Subtract(doj.AddMonths(totalmonths)).Days;

【讨论】:

  • @PanagiotisKanavos - 是的,确实如此。 f = new DateTime(2004, 2, 14), t = new DateTime(2004, 3, 13) => 28 天。 f = new DateTime(2005, 2, 14), t = new DateTime(2005, 3, 13) => 27 天。
  • 对不起,事实上我想知道这是否完全等同于 this 答案,从头到尾计算年等,只是更短。
  • @PanagiotisKanavos - 您链接的代码中也存在错误。尝试使用日期 2020-02-29 到 2021-06-29 运行该代码 - 它返回“1y 4m 1d”,而它应该是“1y 4m 0d”(我的代码返回)。该代码中的错误似乎是由于理解了.AddMonths(1) 在应用于2015-01-30 时的工作原理——它返回2015-02-28。因此,计算结果会缩短几天。
【解决方案2】:

您无法将天数转换为年月和日,因为您不知道那些日子在哪里。例如,它们可能跨越闰年的 2 月 29 日。

但是您已经有两个日期可以使用,因此您可以像这样计算这个值:

Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click

    Dim doj As Date = New Date(2000, 2, 14)
    Dim dor As Date = New Date(2013, 8, 8)

    MessageBox.Show(GetDateSpanText(doj, dor))

End Sub

Public Shared Function GetDateSpanText(fromDate As DateTime, Optional toDate As DateTime = Nothing) As String
    Try
        Dim years As Integer = 0, months As Integer = 0, days As Integer = 0
        If toDate = Nothing Then toDate = DateTime.Now

        Do Until toDate.AddYears(-1) < fromDate
            years += 1
            toDate = toDate.AddYears(-1)
        Loop

        Do Until toDate.AddMonths(-1) < fromDate
            months += 1
            toDate = toDate.AddMonths(-1)
        Loop

        Do Until toDate.AddDays(-1) < fromDate
            days += 1
            toDate = toDate.AddDays(-1)
        Loop

        Return String.Format("{0} Years {1} Months {2} Days", years, months, days)
    Catch ex As Exception
        Return "Error"
    End Try
End Function

【讨论】:

  • 其实你可以通过System.Globalization.Calendar类来提问。不过,您不需要这样做,因为您可以计算年份和月份部分之间的差异。剩余的天数可以计算为 TimeSpan。这显示在answer
【解决方案3】:

您可以使用月份计算年份和月份,如果您有 30 个月,则使用以下代码将返回 2 年和 6 个月。

Math.Round((double)Months/12,0) Years and Month%12 Months

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    相关资源
    最近更新 更多