浏览代码

add:获取上个月第一天和最后一天

zoie 2 周之前
父节点
当前提交
09c80fde6e
共有 1 个文件被更改,包括 36 次插入0 次删除
  1. 36 0
      lib/lib.go

+ 36 - 0
lib/lib.go

@@ -16,6 +16,10 @@ import (
 	"time"
 )
 
+const timeFormat = "2006-01-02 15:04:05"
+const timezone = "Asia/Shanghai"
+const dateFormat = "2006-01-02"
+
 type JSONS struct {
 	//必须的大写开头
 	Code int16
@@ -511,3 +515,35 @@ func ChunkBy[T any](list []T, size int) [][]T {
 	}
 	return append(chunks, list)
 }
+
+// GetFirstDayOfLastMonth 获取上个月第一天的日期
+// 返回格式: 2006-01-02
+func GetFirstDayOfLastMonth() string {
+	loc, _ := time.LoadLocation(timezone)
+	now := time.Now().In(loc)
+
+	// 获取上个月
+	lastMonth := now.AddDate(0, -1, 0)
+
+	// 设置为上个月的第一天
+	firstDay := time.Date(lastMonth.Year(), lastMonth.Month(), 1, 0, 0, 0, 0, loc)
+
+	// 按照日期格式输出
+	return firstDay.Format(dateFormat)
+}
+
+// GetLastDayOfLastMonth 获取上个月最后一天的日期
+// 返回格式: 2006-01-02
+func GetLastDayOfLastMonth() string {
+	loc, _ := time.LoadLocation(timezone)
+	now := time.Now().In(loc)
+
+	// 获取本月的第一天
+	firstDayOfCurrentMonth := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, loc)
+
+	// 本月第一天减去一天,就是上个月的最后一天
+	lastDayOfLastMonth := firstDayOfCurrentMonth.Add(-time.Hour * 24)
+
+	// 按照日期格式输出
+	return lastDayOfLastMonth.Format(dateFormat)
+}