[英]Calculate days in years and months?
如何计算c#中的年数和月数? 每个例子:
如果1. days = 385
然后我需要显示Year= 1.1
(即1年1个月)2。 days= 234
然后我需要显示year =0.7
(即0年7个月)
我们如何计算c#?
我做了days=234 /365
,结果是0.64(即0年6个月)。 但实际上是7个月。
如何获得准确的年份和月份。
你可以做:
double temp = (234.0 /365.0) * 12.0;
int years = (int)temp;
int months = (int)(temp - years);
这是因为你得到0.64,这是0.64年。 如果你想要几个月,你需要乘以12倍。
在上面,你会得到0年零7个月......话虽如此,我不确定你想要如何格式化:
string yearsString = string.Format("{0}.{1}", years, months);
请注意,这将持续11个月3.11,这将是奇怪的,虽然这是你的要求。
此外,如果您希望这一点非常通用,您可能希望使用365.25而不是365来表示单个Julian年 ,因为它可以帮助您减少由于闰年引起的问题。
如果您不知道实际日期,那么您可以估算:
Number of years: x / 365
Number of months: (x % 365) / 30
其中%是模数
假设一个月恰好是一年的十二分之一,并且你想要忽略部分月份(根据你的说法,你希望你的例子有7.688个月,那么:
int days = 234;
double years = (double)days / 365.242199;
int wholeYears = (int)Math.Floor(years);
double partYears = years - wholeYears;
double approxMonths = partYears * 12;
string horribleFormat = string.Concat(wholeYears, ".", approxMonths);
你确定要这种格式吗? 结果 - 至少在提供当前信息的情况下 - 将是模糊的,因为月份是不一致的长度。
考虑几个替代方案:
仅限年份的表示,例如1.25表示“1和四分之一年”。 这不会混合数月和数年,因此一年也很简单,因为一年是365天(闰年除外)。 它还消除了歧义,例如“1.10 == 1.1?”
使用具体的开始日期,允许您使用强类型日期。 您可以轻松地使用带有日期格式参数的.ToString()
来快速准确地获取结果。
我们做一些计算。
1 mon = 0.1 2 mon = 0.2 . . 9 mon = 0.9 10 mon = 1.0 [WRONG according to you 1 is a year] fine then 1 / 12 = 0.083, therefore 0.083 is 1 month Now, 234 / 365 = 0.64 => 0.64 / 0.083 => 7.7 i.e. 7th month Therefore fx => days / 365 = ans % 0.083 = result.
我没有时间证明其他数字,但你可以尝试这个公式。
我的建议是使用DateTime.AddDays:它将为您提供所需的一切。 您还可以在那里添加其他时间单位:
DateTime f = new DateTime(0);
var y = f.AddDays(361);
伪代码
ts= TimeSpan.fromDays(385)
Years = ts.days Modulo 365
months = (ts.days remainder 365) modulo 12
days = (ts.days remainder 365) Remainder 12
answer string years + "." + months + "." + days
在VB中
Dim d As DateTime = DateTime.MinValue 'year = 0001
d = d.AddYears(DateTime.Now.Year - 1) 'add current year
d = d.AddDays(234) 'add days
Dim yrs As Integer = d.Year - DateTime.Now.Year 'calculate years
Dim mos As Double = d.Month / 12 'calculate months
Dim answer As Double = yrs + mos
回答= .6666666666
我认为这在数字上是不可能的。 1年11个月你会做什么? 1.11? 因为这可能意味着1年1个月和1年11个月。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.