Format A TimeSpan With Years

后端 未结 6 1224
深忆病人
深忆病人 2020-11-27 06:45

I have a class with 2 date properties: FirstDay and LastDay. LastDay is nullable. I would like to generate a string in the format of

6条回答
  •  青春惊慌失措
    2020-11-27 07:39

    A TimeSpan doesn't have a sensible concept of "years" because it depends on the start and end point. (Months is similar - how many months are there in 29 days? Well, it depends...)

    To give a shameless plug, my Noda Time project makes this really simple though:

    using System;
    using NodaTime;
    
    public class Test
    {
        static void Main(string[] args)
        {
            LocalDate start = new LocalDate(2010, 6, 19);
            LocalDate end = new LocalDate(2013, 4, 11);
            Period period = Period.Between(start, end,
                                           PeriodUnits.Years | PeriodUnits.Days);
    
            Console.WriteLine("Between {0} and {1} are {2} years and {3} days",
                              start, end, period.Years, period.Days);
        }
    }
    

    Output:

    Between 19 June 2010 and 11 April 2013 are 2 years and 296 days
    

提交回复
热议问题