C#学习教程:如何将天数转换为年、月、日下面视图中如何指定:Convertdaysnumberofyears,numberofmonthsandtherestinthenumberofdaysto(numberofyears,numberofnumbersandrestinthenumberofdays)没有“outofthe盒子的解决方案。问题是您正在处理可变数据,即并非所有年份都是365天,在闰年它变为366。此外,并非每个月都可以假设有标准的30天。在没有上下文的情况下计算此类信息非常困难-但是,您需要以天为单位(至少准确地)计算您需要上下文的年/月数。例如,您需要知道您正在处理的特定月份和特定年份以确定该年是否是闰年,或者该特定月份是否有30/31天等......根据您的评论和以下条件,下面的代码就完成了ThisworksDateTimestartDate=newDateTime(2010,1,1);DateTimeendDate=newDateTime(2013,1,10);vartotalDays=(endDate-startDate).TotalDays;vartotalYears=Math.Truncate(totalDays/365);vartotalMonths=Math.Truncate((totalDays%365)/30);varremainingDays=Math.Truncate((totalDays%365)%30);Console.WriteLine("预计持续时间为{0}年{1}个月{2}天",totalYears,totalMonths,remainingDays);你不能因为它取决于开始日期,即30天可能是1个月1天,或1个月2天,或者少于一个月或365天将少于一年,如果它是闰年如中所述以前的答案,这几天很难解决。闰年和月中的天数有问题。如果你从原来的两个日期时间开始,你可以使用类似的代码:DateTimedate1=newDateTime(2010,1,18);DateTimedate2=newDateTime(2013,2,22);intoldMonth=date2.Month;while(oldMonth==date2.Month){date1=date1.AddDays(-1);date2=date2.AddDays(-1);}intyears=0,months=0,days=0,hours=0,minutes=0,seconds=0,milliseconds=0;//获取年数while(date2.CompareTo(date1)>=0){years++;date2=date2.AddYears(-1);}date2=date2.AddYears(1);年-;//获取月数和天数oldMonth=date2.Month;while(date2.CompareTo(date1)>=0){days++;date2=date2.AddDays(-1);如果((date2.CompareTo(date1)>=0)&&(oldMonth!=date2.Month)){months++;天=0;oldMonth=date2.Month;}}date2=date2.AddDays(1);天-;=date2.Subtract(date1);Console.WriteLine("差异:"+years.ToString()+"year(s)"+","+months.ToString()+"month(s)"+","+days.ToString()+"天)”);输出是:差异reence:3year(s),1month(s),4day(s)以上是C#学习教程:如何将天数转换为年月日。如果对大家有用,需要了解更多关于C#的学习教程,希望大家多多关注——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
