c# - 如何从给定的数字计算年和月

时间:2021-02-15 04:14:31

标签: c# windows visual-studio windows-forms-designer timespan

我需要根据给定的数字计算年和月。我该怎么做? 例如: 我给:26 我需要得到结果:2 年 2 个月 请帮忙

1 个答案:

答案 0 :(得分:1)

除非您有一些更具体的要求,否则它应该像整数除法和 Remainder operator % 一样简单

var input = 26;
var years = input / 12;
var months = input % 12;

Console.WriteLine($"{years} years and {months} months");

输出

2 years and 2 months

private static (int Years, int Months) GetYearsAndMonths(int input) 
   => (input / 12, input % 12);

...

var result = GetYearsAndMonths(26);

Console.WriteLine($"{result.Years} years and {result.Months} months");

或由 Math.DivRem Method

提供的鲜为人知的方法 @Charlieface <块引用>

计算两个数的商并返回余数 在输出参数中。

相关问题