go 時間操作
阿新 • • 發佈:2020-12-13
package common
import (
"fmt"
"strings"
"time"
)
const DATE_FORMAT = "2006-01-02 15:04:05"
const DATE_FORMAT_YMD = "2006-01-02"
//獲取時間差, 返回天時分秒
func GetTimeDiffer(start, end time.Time) (d, h, m, s int64) {
var day, hour, minute, second int64
if start.Before(end) {
timeDiffer := end.Unix() - start.Unix()
day := timeDiffer / (60 * 60 * 24)
hour := (timeDiffer - (60 * 60 * 24 * day)) / 3600
minute := (timeDiffer - 60*60*24*day - 3600*hour) / 60
second := timeDiffer - 60*60*24*day - 3600*hour - 60*minute
return day, hour, minute, second
} else {
return day, hour, minute, second
}
}
//獲取開始&結束時間 每天
func GetStartAndEndTime(date time.Time) (startTime string, endTime string) {
startDate := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.Local)
endDate := time.Date(date.Year(), date.Month(), date.Day(), 23, 59, 59, 0, time.Local)
startTime = startDate.Format("2006-01-02 15:04:05")
endTime = endDate.Format("2006-01-02 15:04:05")
return
}
//獲取開始&結束時間 每月
func GetStartAndEndTimeMonthlyDay(date time.Time) (startTime string, endTime string) {
startDate := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local)
endDate := time.Date(date.Year(), date.Month(), MonthDayCount(date.Year(), date.Month()), 23, 59, 59, 0, time.Local)
startTime = startDate.Format("2006-01-02")
endTime = endDate.Format("2006-01-02")
return
}
//每月天數
func MonthDayCount(year int, month time.Month) (days int) {
var m int
m = int(month)
if m != 2 {
if m == 4 || m == 6 || m == 9 || m == 11 {
days = 30
} else {
days = 31
}
} else {
if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
days = 29
} else {
days = 28
}
}
return days
}
//格式化時間(字串轉time) date 必須是 '2019-09-01 12:11:11' 格式
func GetTimeTypeByString(date string) time.Time {
applyTime, _ := time.ParseInLocation("2006-01-02 15:04:05", date, time.Local)
return applyTime
}
//格式化時間(字串轉time) date 必須是 '2019-09-01' 格式
func GetTimeDateTypeByString(date string) time.Time {
applyTime, _ := time.ParseInLocation("2006-01-02", date, time.Local)
return applyTime
}
func FormatTime(timestamp int64) string {
if timestamp == 0 {
timestamp = time.Now().Unix()
}
return time.Unix(timestamp, 0).Format("2006-01-02 15:04:05")
}
func GetDurationDays(startTime int64, endTime int64) []string {
var result []string
dayTime := int64(3600 * 24)
nowTime := time.Now().Unix()
if endTime == 0 || endTime > nowTime {
endTime = nowTime
}
if startTime == 0 || startTime > nowTime {
startTime = nowTime
}
for {
if startTime > endTime {
break
}
result = append(result, time.Unix(startTime, 0).Format("2006-01-02"))
startTime += dayTime
}
return result
}