go在工作中常用的日期处理函数,复制即可使用

package utils

import (
	"fmt"
	"time"
)

// GetLastMonthDates 返回上个月的第一天和最后一天的time.Time类型值
func GetLastMonthDates(now time.Time) (time.Time, time.Time) {
	var firstDay, lastDay time.Time
	if now.Month() == 1 {
		firstDay = time.Date(now.Year()-1, 12, 1, 0, 0, 0, 0, time.UTC)
	} else {
		firstDay = time.Date(now.Year(), now.Month()-1, 1, 0, 0, 0, 0, time.UTC)
	}
	lastDay = firstDay.AddDate(0, 1, -1)
	return firstDay, lastDay
}

// GetLastMonthDatesFormat 返回一个字符串切片,包含上个月的起始日期和结束日期,格式为传入的format
// format:时间格式字符串,如"2006-01-02"
// 返回值:
// - string:上个月的起始日期,按照format格式化
// - string:上个月的结束日期,按照format格式化
func GetLastMonthDatesFormat(now time.Time, format string) (string, string) {
	firstDay, lastDay := GetLastMonthDates(now)
	return firstDay.Format(format), lastDay.Format(format)
}

// GetMonthDays 根据给定的年月字符串返回该月有多少天
//
// 参数:
//
//	yearMonth string - 表示年月的字符串,格式为"200601"
//
// 返回值:
//
//	int - 表示该月有多少天
//	error - 如果输入的年月格式不正确或解析出错,则返回错误信息;否则为nil
func GetMonthDays(yearMonth, layout string) (int, error) {
	if len(yearMonth) != len(layout) {
		return -1, fmt.Errorf("invalid date")
	}
	t, err := time.Parse(layout, yearMonth)
	if err != nil {
		return -1, err
	}
	return t.AddDate(0, 1, -t.Day()).Day(), nil
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值