GO 常用工具函数
// 求两个时间戳(单位 秒)之间间隔的自然天数
//
// 2022-07-04 00:00 2022-07-05 xx:xx => 1
// 2022-07-04 00:00 2022-07-04 xx:xx => 0
func DiffIntervalNatureDays(t1, t2 int64) int64 {
var (
diffDays int64
SecondsOfDay int64 = 60 * 60 * 24
)
if t1 == t2 {
return 0
}
if t1 > t2 {
t1, t2 = t2, t1
}
secDiff := t2 - t1
if secDiff > SecondsOfDay {
tmpDays := secDiff / SecondsOfDay // int计算会舍去小数位
t1 += tmpDays * SecondsOfDay
diffDays += tmpDays
}
st := time.Unix(t1, 0)
et := time.Unix(t2, 0)
dateFormatTpl := "20060102"
if st.Format(dateFormatTpl) != et.Format(dateFormatTpl) {
diffDays += 1
}
return diffDays
}
// 求两个时间戳(单位 秒)之间的自然天数
//
// 2022-07-04 00:00 2022-07-05 xx:xx => 2
// 2022-07-04 00:00 2022-07-04 xx:xx => 1
func DiffNatureDays(t1, t2 int64) int64 {
var (
diffDays int64 = 1
SecondsOfDay int64 = 60 * 60 * 24
)
if t1 == t2 {
return diffDays
}
if t1 > t2 {
t1, t2 = t2, t1
}
secDiff := t2 - t1
if secDiff >= SecondsOfDay {
tmpDays := secDiff / SecondsOfDay // int计算会舍去小数位
diffDays += tmpDays
}
return diffDays
}
import (
"bytes"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
"io/ioutil"
)
//UTF82GBK : transform UTF8 rune into GBK byte array
func UTF82GBK(src string) ([]byte, error) {
GB18030 := simplifiedchinese.All[0]
return ioutil.ReadAll(transform.NewReader(bytes.NewReader([]byte(src)), GB18030.NewEncoder()))
}
//GBK2UTF8 : transform GBK byte array into UTF8 string
func GBK2UTF8(src []byte) (string, error) {
GB18030 := simplifiedchinese.All[0]
bytes, err := ioutil.ReadAll(transform.NewReader(bytes.NewReader(src), GB18030.NewDecoder()))
return string(bytes), err
}