Golang获取月份的第一天和最后一天

package main

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

func main() {
	month := "2023-11"
	result := GetMonthStartAndEnd(month)
	fmt.Println(result["start"] + " - " + result["end"])
}

// 获取月份的第一天和最后一天 month 格式:2023-11
func GetMonthStartAndEnd(month string) map[string]string {
	v := strings.Split(month, "-")
	myYear := v[0]
	myMonth := v[1]
	// 数字月份必须前置补零
	yInt, _ := strconv.Atoi(myYear)
	timeLayout := "2006-01-02 15:04:05"
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
	newMonth := theTime.Month()

	t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
	t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
	result := map[string]string{"start": t1, "end": t2}
	return result
}

你可能感兴趣的:(golang,服务器)