2 Star 0 Fork 0

TeamsHub/backend-gopkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
time_parse.go 2.59 KB
一键复制 编辑 原始数据 按行查看 历史
HCY 提交于 2024-07-16 14:47 . v1.5.10
package time_parse
import (
"fmt"
"github.com/araddon/dateparse"
"math"
"net/http"
"strings"
"time"
)
var (
cst *time.Location
)
// CSTLayout China Standard Time Layout
const CSTLayout = "2006-01-02 15:04:05"
func init() {
var err error
if cst, err = time.LoadLocation("Asia/Shanghai"); err != nil {
panic(err)
}
}
// RFC3339ToCSTLayout convert rfc3339 value to china standard time layout
// 2020-11-08T08:18:46+08:00 => 2020-11-08 08:18:46
func RFC3339ToCSTLayout(value string) (string, error) {
ts, err := time.Parse(time.RFC3339, value)
if err != nil {
return "", err
}
return ts.In(cst).Format(CSTLayout), nil
}
// CSTLayoutString 格式化时间
// 返回 "2006-01-02 15:04:05" 格式的时间
func CSTLayoutString() string {
ts := time.Now()
return ts.In(cst).Format(CSTLayout)
}
// ParseCSTInLocation 格式化时间
func ParseCSTInLocation(date string) (time.Time, error) {
return time.ParseInLocation(CSTLayout, date, cst)
}
// CSTLayoutStringToUnix 返回 unix 时间戳
// 2020-01-24 21:11:11 => 1579871471
func CSTLayoutStringToUnix(cstLayoutString string) (int64, error) {
stamp, err := time.ParseInLocation(CSTLayout, cstLayoutString, cst)
if err != nil {
return 0, err
}
return stamp.Unix(), nil
}
// GMTLayoutString 格式化时间
// 返回 "Mon, 02 Jan 2006 15:04:05 GMT" 格式的时间
func GMTLayoutString() string {
return time.Now().In(cst).Format(http.TimeFormat)
}
// ParseGMTInLocation 格式化时间
func ParseGMTInLocation(date string) (time.Time, error) {
return time.ParseInLocation(http.TimeFormat, date, cst)
}
// SubInLocation 计算时间差
func SubInLocation(ts time.Time) float64 {
return math.Abs(time.Now().In(cst).Sub(ts).Seconds())
}
// SplitTimeByDay 根据时间划分时间段
func SplitTimeByDay(start, end time.Time, days int) [][]time.Time {
var times [][]time.Time
for {
var ts []time.Time
ts = append(ts, start)
endTime := start.AddDate(0, 0, days)
if end.After(endTime) {
ts = append(ts, endTime)
times = append(times, ts)
} else {
ts = append(ts, end)
times = append(times, ts)
return times
}
start = endTime
}
}
type SelfTime time.Time
func (t *SelfTime) UnmarshalJSON(data []byte) (err error) {
fmt.Println(string(data))
now, err := dateparse.ParseLocal(strings.Trim(string(data), "\""))
fmt.Println(now)
*t = SelfTime(now)
fmt.Println(time.Time(*t))
return
}
func (t SelfTime) String() string {
return time.Time(t).Format(CSTLayout)
}
// 13位时间戳
func TimeTo13Unix(e time.Time) int64 {
timeUnix, _ := time.Parse("2006-01-02 15:04:05", e.Format("2006-01-02 15:04:05"))
return timeUnix.UnixNano() / 1e6
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wuzheng0709/backend-gopkg.git
git@gitee.com:wuzheng0709/backend-gopkg.git
wuzheng0709
backend-gopkg
backend-gopkg
v1.5.22

搜索帮助