由于业务需求,在系统中计算任务需要花费多少时间,并按开始时间和结束时间来计算,可以得到多少年、多少个月、多少天,如果是同一天就需要得到多少小时、多少分钟、多少秒
public string term(DateTime b, DateTime e)
{
if (b < e)
{
var t = new
{
bm = b.Month,
em = e.Month,
bd = b.Day,
ed = e.Day
};
int diffMonth = (e.Year - b.Year) * 12 + (t.em - t.bm),//相差月
diffYear = diffMonth / 12;//相差年
int[] d = new int[3] { 0, 0, 0 };
if (diffYear > 0)
{
if (t.em == t.bm && t.ed < t.bd)
{
d[0] = diffYear - 1;
}
else d[0] = diffYear;
}
if (t.ed >= t.bd)
{
d[1] = diffMonth % 12;
d[2] = t.ed - t.bd;
}
else//结束日 小于 开始日
{
int dm = diffMonth - 1;
d[1] = dm % 12;
TimeSpan ts = e - b.AddMonths(dm);
d[2] = ts.Days;
}
StringBuilder sb = new StringBuilder();
if (d.Sum() > 0)
{
if (d[0] > 0) sb.Append($"{d[0]}年");
if (d[1] > 0) sb.Append($"{d[1]}个月");
if (d[2] > 0) sb.Append($"{d[2]}天");
}
else
{
int[] time = new int[2] { 0, 0 };
TimeSpan sj = e - b;
time[0] = sj.Hours;
time[1] = sj.Minutes % 60;
if (time[0] > 0) sb.Append($"{time[0]}小时");
if (time[1] > 0) sb.Append($"{time[1]}分钟");
if (time.Sum()<=0)sb.Append($"{sj.Seconds}秒");
}
return sb.ToString();
}
else throw new Exception("开始日期必须小于结束日期");
}