mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-18 00:22:41 +08:00
日期时间转换
This commit is contained in:
12
dateconv/date_test.go
Normal file
12
dateconv/date_test.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package dateconv_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/charlienet/go-mixed/dateconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestToday(t *testing.T) {
|
||||||
|
today := dateconv.Today()
|
||||||
|
t.Log(dateconv.TimeToString(&today))
|
||||||
|
}
|
43
dateconv/dateconv.go
Normal file
43
dateconv/dateconv.go
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
package dateconv
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
layoutDate = "2006-01-02"
|
||||||
|
layoutTime = "2006-01-02 15:04:05"
|
||||||
|
layoutChineseDate = "2006年01月02日"
|
||||||
|
layoutChineseTime = "2006年01月02日 15:04:05"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Today() time.Time {
|
||||||
|
t := time.Now()
|
||||||
|
year, month, day := t.Date()
|
||||||
|
return time.Date(year, month, day, 0, 0, 0, 0, t.Location())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 日期转换为整数(如:20211222)
|
||||||
|
func DateToInt(date time.Time) int {
|
||||||
|
return date.Year()*10000 + int(date.Month())*100 + date.Day()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 日期转换为字符串
|
||||||
|
func DateToString(date *time.Time) string { return formatTime(date, layoutDate) }
|
||||||
|
|
||||||
|
// 时间转换为字符串
|
||||||
|
func TimeToString(date *time.Time) string { return formatTime(date, layoutTime) }
|
||||||
|
|
||||||
|
// 日期转换为中文
|
||||||
|
func DateToChinese(t *time.Time) string { return formatTime(t, layoutChineseDate) }
|
||||||
|
|
||||||
|
// 时间转换为中文
|
||||||
|
func TimeToChinese(t *time.Time) string { return formatTime(t, layoutChineseTime) }
|
||||||
|
|
||||||
|
func formatTime(t *time.Time, f string) string {
|
||||||
|
if t == nil || t.IsZero() {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return t.Format(f)
|
||||||
|
}
|
Reference in New Issue
Block a user