123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- package utils
- import (
- "time"
- )
- const (
- YearMonthDay = "2006-01-02"
- YearMonthDayTime = "2006-01-02 15:04:05"
- MonthDay = "01-02"
- DayMonthYear = "02-01-2006"
- YearMonth = "2006-01"
- FullDate = "Monday, 02-Jan-06 15:04:05 PST"
- )
- func GetPreYearTime(n int) string {
-
- now := time.Now()
-
- preYearTime := now.AddDate(-n, 0, 0)
-
- return preYearTime.Format("2006-01-02")
- }
- func IsMoreThanOneDay(startDate, endDate string) bool {
- startTime, _ := time.Parse("2006-01-02", startDate)
- endTime, _ := time.Parse("2006-01-02", endDate)
- diff := endTime.Sub(startTime)
- days := diff.Hours() / 24
- return days > 1
- }
- func GetNextDay(date string) string {
- t, _ := time.Parse("2006-01-02", date)
- nextDay := t.AddDate(0, 0, 1)
- return nextDay.Format("2006-01-02")
- }
- func GetNextDayN(date string, n int) string {
- t, _ := time.Parse("2006-01-02", date)
- nextDay := t.AddDate(0, 0, n)
- return nextDay.Format("2006-01-02")
- }
- var daysOfMonth = [...]int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
- func AddDate(t time.Time, years, months int) time.Time {
- month := t.Month()
-
- years, months = norm(years, months, 12)
-
- targetMonth := int(month) + months
- if targetMonth <= 0 {
-
- targetMonth += 12 * ((-targetMonth)/12 + 1)
- }
-
- targetMonth = (targetMonth-1)%12 + 1
-
- targetYear := t.Year() + years + (int(month)+months-1)/12
-
- maxDayOfTargetMonth := daysOfMonth[targetMonth-1]
- if isLeap(targetYear) && targetMonth == 2 {
- maxDayOfTargetMonth++
- }
-
- targetDay := t.Day()
- if targetDay > maxDayOfTargetMonth {
-
- targetDay = maxDayOfTargetMonth
- }
-
- return time.Date(targetYear, time.Month(targetMonth), targetDay, t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location())
- }
- func norm(hi, lo, base int) (nhi, nlo int) {
- if lo < 0 {
- n := (-lo-1)/base + 1
- hi -= n
- lo += n * base
- }
- if lo >= base {
- n := lo / base
- hi += n
- lo -= n * base
- }
- return hi, lo
- }
- func isLeap(year int) bool {
- return year%4 == 0 && (year%100 != 0 || year%400 == 0)
- }
- func StringToTime(date string) time.Time {
- t, _ := time.Parse("2006-01-02", date)
- return t
- }
- func TimeToString(t time.Time, format string) string {
- formattedTime := t.Format(format)
- return formattedTime
- }
- func CompareDate(data1, data2 string) bool {
- t1, _ := time.Parse("2006-01-02", data1)
- t2, _ := time.Parse("2006-01-02", data2)
- return !t1.After(t2)
- }
|