用不习惯也嫌麻烦每次都去操作时间,然后就自己写了个时间工具类
package timeutil
import (
"time"
)
func New() *TimeUtil {
return &TimeUtil{}
}
type TimeUtil struct{}
func (tu *TimeUtil) GetFormattedDate(t time.Time) string {
return t.Format("2006-01-02")
}
func (tu *TimeUtil) GetFormattedTime(t time.Time) string {
return t.Format("15:04:05")
}
func (tu *TimeUtil) GetFormattedDateTime(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
}
func (tu *TimeUtil) GetWeekday(t time.Time) string {
return t.Weekday().String()
}
func (tu *TimeUtil) IsLeapYear(year int) bool {
return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}
func (tu *TimeUtil) ParseDateFromString(dateString string) (time.Time, error) {
layout := "2006-01-02"
t, err := time.Parse(layout, dateString)
if err != nil {
return time.Time{}, err
}
return t, nil
}
func (tu *TimeUtil) ParseTimeFromString(timeString string) (time.Time, error) {
layout := "15:04:05"
t, err := time.Parse(layout, timeString)
if err != nil {
return time.Time{}, err
}
return t, nil
}
func (tu *TimeUtil) ParseDateTimeFromString(dateTimeString string) (time.Time, error) {
layout := "2006-01-02 15:04:05"
t, err := time.Parse(layout, dateTimeString)
if err != nil {
return time.Time{}, err
}
return t, nil
}
func (tu *TimeUtil) FormatTimeString(inputTime, format string) (string, error) {
format = rule(format)
layout := "2006-01-02 15:04:05"
t, err := time.Parse(layout, inputTime)
if err != nil {
return "", err
}
formattedTime := t.Format(format)
return formattedTime, nil
}
func (tu *TimeUtil) FormatTimeStringZ(inputTime, format string) (string, error) {
format = rule(format)
t, err := time.Parse(time.RFC3339, inputTime)
if err != nil {
return "", err
}
formattedTime := t.Format(format)
return formattedTime, nil
}
func rule(format string) (str string) {
if format == "1" {
format = "2006-01-02 15:04:05"
} else if format == "2" {
format = "2006-01-02"
} else if format == "3" {
format = "15:04:05"
}
return format
}