time.Time
转YYYY-MM-DD hh:mm:ss
import (
"database/sql"
"fmt"
"time"
)
// FormatMysqlTime 格式化MysqlTime
func FormatMysqlTime(time time.Time) string {
if time.IsZero() {
return ""
}
msg := time.Format("2006-01-02 15:04:05")
return msg
}
time.Time 转 sql.NullTime
func GenMysqlTime(t time.Time) sql.NullTime {
return sql.NullTime{
Time: t,
Valid: true,
}
}
// 时间转换 string to time.Time
func GetTime(t string) time.Time {
parseTime, _ := time.Parse("2006-01-02 15:04:05", t)
return parseTime
}
获取当天00:00:00日期
// 获取当天00:00:00日期
func GetNowZeroTime() string {
zt, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local)
return zt.Format("2006-01-02 15:04:05")
}
获取前七天日期
// 获取前七天日期
func GetListSevenDays() []string {
var times []string
// 时区
timeZone := time.FixedZone("CST", 8*3600) // 东八区
// 前n天
nowTime := time.Now().In(timeZone)
for i := -7; i < 0; i++ {
beforeTime := nowTime.AddDate(0, 0, i).Format("2006-01-02")
times = append(times, beforeTime)
}
return times
}
获取前一个月(自然月)日期
// 获取前一个月(自然月)日期
func GetListMonth() []string {
var times []string
// 时区
timeZone := time.FixedZone("CST", 8*3600) // 东八区
// 前n天
nowTime := time.Now().In(timeZone)
currentTime, _ := time.Parse("2006/01/02", time.Now().Format("2006/01/02"))
startTime, _ := time.Parse("2006/01/02", nowTime.AddDate(0, -1, 0).Format("2006/01/02"))
//天数
dis := currentTime.Sub(startTime)
loveDay := dis.Hours() / 24
//添加日期
for i := -int(loveDay); i < 0; i++ {
beforeTime := nowTime.AddDate(0, 0, i).Format("2006-01-02")
times = append(times, beforeTime)
}
return times
}
获取前六月日期
// 获取前六月日期
func GetListSixMonth() []string {
var times []string
// 时区
timeZone := time.FixedZone("CST", 8*3600) // 东八区
// 前n天
nowTime := time.Now().In(timeZone)
for i := -6; i < 0; i++ {
beforeTime := nowTime.AddDate(0, i, 0).Format("2006-01")
times = append(times, beforeTime)
}
return times
}
获取前一年日期
// 获取前一年日期
func GetListYear() []string {
var times []string
// 时区
timeZone := time.FixedZone("CST", 8*3600) // 东八区
// 前n天
nowTime := time.Now().In(timeZone)
for i := -12; i < 0; i++ {
beforeTime := nowTime.AddDate(0, i, 0).Format("2006-01")
times = append(times, beforeTime)
}
return times
}
复杂时间字符串的转换
// 复杂时间字符串的转换
// `2023-09-20T00:00:00+08:00` 转 `2006-01-02 15:04:05` 格式
func ComplexStringToTime(str string) string {
layout := "2006-01-02T15:04:05-07:00"
// 解析输入的时间字符串
t, err := time.Parse(layout, str)
if err != nil {
fmt.Println("解析错误:", err)
return ""
}
formatted := t.Format("2006-01-02 15:04:05")
return formatted
}
. . .
相关推荐
热门推荐
【华为电脑试题JAVA实现详解】-学英语
29天前
超市搞活动(完全背包)
29天前
sqlserver数据库显示正在恢复
29天前
flex 鼠标中间滚动按钮监听
25天前
SpringBoot-JWT生成
25天前
ads via 小工具