Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DiffInMonths calculation is invalid #165

Closed
wesuccess666 opened this issue Feb 7, 2023 · 2 comments
Closed

DiffInMonths calculation is invalid #165

wesuccess666 opened this issue Feb 7, 2023 · 2 comments
Labels
Bug Report a reproducible bug or regression

Comments

@wesuccess666
Copy link

Hello,

I encountered an issue with the following code:
DiffInMonths is invalid, It's not every month is 30 days

// DiffInMonths gets the difference in months.
// 相差多少月
func (c Carbon) DiffInMonths(carbon ...Carbon) int64 {
	start, end := c, c.Now()
	if len(carbon) > 0 {
		end = carbon[len(carbon)-1]
	}
	return int64(math.Floor(float64((end.Timestamp() - start.Timestamp()) / (30 * 24 * 3600))))
}

In version 1.6.9, DiffInMonths is right

func (c Carbon) DiffInMonths(carbon ...Carbon) int64 {
	end := c.Now()
	if len(carbon) > 0 {
		end = carbon[len(carbon)-1]
	}
	startYear, startMonth, startDay := c.Date()
	endYear, endMonth, endDay := end.Date()

	diffYear, diffMonth, diffDay := endYear-startYear, endMonth-startMonth, endDay-startDay
	if diffDay < 0 {
		diffMonth = diffMonth - 1
	}
	if diffYear == 0 && diffMonth == 0 {
		return int64(0)
	}
	if diffYear == 0 && diffMonth != 0 && diffDay != 0 {
		if int(end.DiffAbsInHours(c)) < c.DaysInMonth()*HoursPerDay {
			return int64(0)
		}
		return int64(diffMonth)
	}
	return int64(diffYear*MonthsPerYear + diffMonth)
}

Thanks!

@wesuccess666 wesuccess666 added the Bug Report a reproducible bug or regression label Feb 7, 2023
@gouguoyin
Copy link
Member

The next version will fix

@gouguoyin
Copy link
Member

Fixed in version 2.2.4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Report a reproducible bug or regression
Development

No branches or pull requests

2 participants