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

About calculating how many months are the difference between two times #255

Closed
SFLAQiu opened this issue Nov 11, 2024 · 2 comments
Closed
Labels
Question Indicates that an issue, pull request, or discussion needs more information

Comments

@SFLAQiu
Copy link

SFLAQiu commented Nov 11, 2024

Hello,

About the difference between the two time months, the calculation output is 1 month

s := "2024-10-11"
e := "2024-11-10"
fmt.Println(carbon.Parse(s).DiffAbsInDays(carbon.Parse(e)))
fmt.Println("carbon v2 = ", carbon.Parse(s).DiffInMonths(carbon.Parse(e)))

// print
// 30
// carbon v2 =  1

PHP carbon calculation output: 0 month difference
PHP carbon

echo Carbon::parse("2024-10-11")->diffInMonths("2024-11-10");

// print
// 0

golang version: such as 1.20
carbon version: such as 2.4.1

problem
I personally feel that php carbon's calculation is reasonable, and if the natural month does not meet a month, it should be 0, rather than judging by 28 to return 0 ,Is there a problem with this calculation? Does it need fixing?

func (c Carbon) DiffInMonths(carbon ...Carbon) int64 {
	end := c.Now()
	if c.IsSetTestNow() {
		end = CreateFromTimestampNano(c.testNow, c.Location())
	}
	if len(carbon) > 0 {
		end = carbon[0]
	}
	if c.DiffAbsInDays(end) < 28 {
		return 0
	}
	startYear, startMonth, _ := c.Date()
	endYear, endMonth, _ := end.Date()
	diffYear, diffMonth := endYear-startYear, endMonth-startMonth
	return int64(diffYear*MonthsPerYear + diffMonth)
}

Thanks!

@SFLAQiu SFLAQiu added the Question Indicates that an issue, pull request, or discussion needs more information label Nov 11, 2024
@gouguoyin
Copy link
Collaborator

I will compare the PHP version of Carbon

gouguoyin added a commit that referenced this issue Nov 24, 2024
gouguoyin added a commit that referenced this issue Nov 25, 2024
@gouguoyin
Copy link
Collaborator

v2.5.0 has been fixed and released, the unit test is as follows

func TestCarbon_Issue255(t *testing.T) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question Indicates that an issue, pull request, or discussion needs more information
Projects
None yet
Development

No branches or pull requests

2 participants