可以通过将日期字符串转换为时间类型,然后计算两个时间的月份差来实现。具体代码如下:

package main

import (
    "fmt"
    "time"
)

func MonthDiff(from, to string) int {
    fromTime, _ := time.Parse("2006-01-02", from)
    toTime, _ := time.Parse("2006-01-02", to)
    yearDiff := toTime.Year() - fromTime.Year()
    monthDiff := int(toTime.Month()) - int(fromTime.Month())
    totalMonthDiff := yearDiff*12 + monthDiff
    return totalMonthDiff
}

func main() {
    from := "2021-01-01"
    to := "2022-06-30"
    monthDiff := MonthDiff(from, to)
    fmt.Printf("%s 和 %s 相差 %d 个月\n", from, to, monthDiff)
}

输出结果为:

2021-01-01 和 2022-06-30 相差 17 个月

在上面的代码中,MonthDiff 函数接收两个日期字符串参数 from 和 to,然后使用 time.Parse 将它们转换为时间类型。接着,计算两个时间的年份差和月份差,最后将它们转换为总的月份差并返回。在 main 函数中,我们测试了该函数的使用方法。

golang开发有两个日期格式为Y-m-d计算两个日期相差的月份

原文地址: https://www.cveoy.top/t/topic/bU1l 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录