简体   繁体   English

找出月份中的整数差

[英]Finding the difference in months as integers

I have two vectors that represent months ie 1 as January 2 as February, etc... how do we find the difference between months without getting negative values? 我有两个向量表示月份,即1表示1月2日表示2月,依此类推...如何在不得到负值的情况下找到月份之间的差异?

Example

dates1 = [1, 3, 1]; date1 = [1、3、1];

dates2 = [12, 1, 0]; date2 = [12,1,0];

Expected: dates2 - dates1 = [11, 10, 11] 预期:dates2-dates1 = [11,10,11]

Actual: [11, -2, -1] 实际:[11,-2,-1]

If you have two months a and b , and b is after a , and b may possibly be in the following year, you can just use something like: 如果您有两个月ab ,并且ba之后,并且b可能在第二年,则可以使用以下方法:

diff = (b + 12 - a) % 12;

The adding of twelve to b ensures that it is greater than a (effectively moving it into the following year) and the use of modulo ensures the adding of twelve doesn't move it two years beyond a . b加12可以确保它大于a (有效地将其移入下一年),并且使用模数确保b不能将a 2超过a

You can use modulo arithmetic: 您可以使用取模算法:

const int MONTHS_PER_YEAR = 12;
int difference = ((month_1 + MONTHS_PER_YEAR) - month_2) % MONTHS_PER_YEAR;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM