【问题标题】:Date month and year calculation [duplicate]日期月份和年份计算[重复]
【发布时间】:2015-06-20 22:44:51
【问题描述】:

我有两个日期的表格:

Start Date: 2007-03-24 
End Date: 2009-06-26

现在我需要用下面的形式找出这两者之间的区别:

2 years, 3 months and 2 days

如何在 c# windows 窗体中执行此操作?

【问题讨论】:

    标签: c#


    【解决方案1】:

    您需要使用TimeSpan 来获得差异..

     class Program
        {
            static void Main(string[] args)
            {
    
                string StartDate = "2007-03-24";
                string EndDate = "2009-06-26";
    
                System.DateTime firstDate = DateTime.ParseExact(StartDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                System.DateTime secondDate = DateTime.ParseExact(EndDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
    
                System.TimeSpan diff = secondDate.Subtract(firstDate);
                var totalDays = (diff).TotalDays;
                var totalYears = Math.Truncate(totalDays / 365);
                var totalMonths = Math.Truncate((totalDays % 365) / 30);
                var remainingDays = Math.Truncate((totalDays % 365) % 30);
                Console.WriteLine("Estimated duration is {0} year(s), {1} month(s) and {2} day(s)", totalYears, totalMonths, remainingDays);
                Console.ReadLine();
    
            }
    
        }
    

    【讨论】:

      【解决方案2】:

      .net 已经提供 TimeSpan 类来显示两个日期时间值之间的差异。TimeSpan 类的一些属性分别显示年、月和日间隔

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-27
        • 1970-01-01
        • 1970-01-01
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多