github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/time/time.go (about)

     1  package time
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"math"
     7  	"regexp"
     8  	"strconv"
     9  	"strings"
    10  	t0 "time"
    11  )
    12  
    13  var (
    14  	Year   = "2006"
    15  	Month  = "01"
    16  	Day    = "02"
    17  	Hour   = "15"
    18  	Minute = "04"
    19  	Second = "05"
    20  
    21  	FmtYMdHmsSSS = "2006-01-02 15:04:05.000"
    22  	FmtYMdHmsS   = "2006-01-02 15:04:05.0"
    23  	FmtYMdHms    = "2006-01-02 15:04:05"
    24  	FmtYMdHm     = "2006-01-02 15:04"
    25  	FmtYMdH      = "2006-01-02 15"
    26  	FmtYMd       = "2006-01-02"
    27  	FmtYM        = "2006-01"
    28  	FmtY         = "2006"
    29  	FmtYYYYMMdd  = "20060102"
    30  
    31  	FmtHmsSSSMore = "15:04:05.000000000"
    32  	FmtHmsSSS     = "15:04:05.000"
    33  	FmtHms        = "15:04:05"
    34  	FmtHm         = "15:04"
    35  	FmtH          = "15"
    36  
    37  	EmptyTime = t0.Time{}
    38  
    39  	yRegex        = regexp.MustCompile("^(\\d){4}$")
    40  	yyyyMmDdRegex = regexp.MustCompile("^(\\d){4}(\\d){2}(\\d){2}$")
    41  	ymRegex       = regexp.MustCompile("^(\\d){4}-(\\d){2}$")
    42  	ymdRegex      = regexp.MustCompile("^(\\d){4}-(\\d){2}-(\\d){2}$")
    43  	ymdHRegex     = regexp.MustCompile("^(\\d){4}-(\\d){2}-(\\d){2} (\\d){2}$")
    44  	ymdHmRegex    = regexp.MustCompile("^(\\d){4}-(\\d){2}-(\\d){2} (\\d){2}:(\\d){2}$")
    45  	ymdHmsRegex   = regexp.MustCompile("^(\\d){4}-(\\d){2}-(\\d){2} (\\d){2}:(\\d){2}:(\\d){2}$")
    46  	ymdHmsSRegex  = regexp.MustCompile("^(\\d){4}-(\\d){2}-(\\d){2} (\\d){2}:(\\d){2}:(\\d){2}.(\\d){3}$")
    47  )
    48  
    49  type FPCDateTime float64
    50  
    51  const (
    52  	DateDelta   = 693594 // Days between 1/1/0001 and 12/31/1899
    53  	HoursPerDay = 24
    54  	MinsPerHour = 60
    55  	SecsPerMin  = 60
    56  	MSecsPerSec = 1000
    57  
    58  	MinsPerDay  = HoursPerDay * MinsPerHour
    59  	SecsPerHour = SecsPerMin * MinsPerHour
    60  	SecsPerDay  = MinsPerDay * SecsPerMin
    61  	MSecsPerDay = SecsPerDay * MSecsPerSec
    62  
    63  	OneMillisecond  = FPCDateTime(1) / MSecsPerDay
    64  	HalfMilliSecond = OneMillisecond / 2
    65  
    66  	JulianEpoch = FPCDateTime(-2415018.5)
    67  	UnixEpoch   = JulianEpoch + FPCDateTime(2440587.5)
    68  
    69  	ApproxDaysPerMonth = 30.4375
    70  	ApproxDaysPerYear  = 365.25
    71  )
    72  
    73  func TimeToStringYmdHms(t t0.Time) string {
    74  	return t.Format(FmtYMdHms)
    75  }
    76  
    77  func TimeToStringYmdHmsS(t t0.Time) string {
    78  	return t.Format(FmtYMdHmsSSS)
    79  }
    80  
    81  func TimeToStringFormat(t t0.Time, format string) string {
    82  	return t.Format(format)
    83  }
    84  
    85  func ParseTimeYmsHms(timeStr string) (t0.Time, error) {
    86  	return t0.ParseInLocation(Year+"-"+Month+"-"+Day+" "+Hour+":"+Minute+":"+Second, timeStr, t0.Local)
    87  }
    88  
    89  func ParseTimeYmsHmsS(timeStr string) (t0.Time, error) {
    90  	return t0.ParseInLocation(Year+"-"+Month+"-"+Day+" "+Hour+":"+Minute+":"+Second+".000", timeStr, t0.Local)
    91  }
    92  
    93  func ParseTimeYmsHmsLoc(timeStr string, loc *t0.Location) (t0.Time, error) {
    94  	return t0.ParseInLocation(Year+"-"+Month+"-"+Day+" "+Hour+":"+Minute+":"+Second, timeStr, loc)
    95  }
    96  
    97  func ParseTimeYmsHmsSLoc(timeStr string, loc *t0.Location) (t0.Time, error) {
    98  	return t0.ParseInLocation(Year+"-"+Month+"-"+Day+" "+Hour+":"+Minute+":"+Second+".000", timeStr, loc)
    99  }
   100  
   101  // TimeInMillis 13位java时间戳
   102  func TimeInMillis() int64 {
   103  	return t0.Now().UnixMilli()
   104  }
   105  
   106  // TimeInSeconds 10位Unix时间戳
   107  func TimeInSeconds() int64 {
   108  	return t0.Now().Unix()
   109  }
   110  
   111  // TimeInMicro 16位时间戳
   112  func TimeInMicro() int64 {
   113  	return t0.Now().UnixMicro()
   114  }
   115  
   116  // TimeInNano 19位时间戳
   117  func TimeInNano() int64 {
   118  	return t0.Now().UnixNano()
   119  }
   120  
   121  //====================================================================================
   122  // 时间日期函数
   123  //====================================================================================
   124  
   125  func CurrentMinuteOfDay() int {
   126  	t := t0.Now()
   127  	return t.Hour()*60 + t.Minute()
   128  }
   129  
   130  func CurrentSecondOfDay() int {
   131  	t := t0.Now()
   132  	return t.Hour()*3600 + t.Minute()*60 + t.Second()
   133  }
   134  
   135  func MinuteOfDay(t t0.Time) int {
   136  	return t.Hour()*60 + t.Minute()
   137  }
   138  
   139  func SecondOfDay(t t0.Time) int {
   140  	return t.Hour()*3600 + t.Minute()*60 + t.Second()
   141  }
   142  
   143  func MinutesToTime(minutes int) (hour int, minute int) {
   144  	h0 := minutes / 60
   145  	m0 := minutes % 60
   146  	return h0, m0
   147  }
   148  
   149  func SecondsToTime(seconds int) (hour int, minute int, second int) {
   150  	h0, m0 := MinutesToTime(seconds / 60)
   151  	s0 := seconds % 60
   152  	return h0, m0, s0
   153  }
   154  
   155  func IsLeapYear(year int) bool {
   156  	return (year%4 == 0) && ((year%100 != 0) || (year%400 == 0))
   157  }
   158  
   159  func YearsBetween(now, then t0.Time) int {
   160  	return int(math.Trunc(now.Sub(then).Hours() / 24 / ApproxDaysPerYear))
   161  }
   162  
   163  func MonthsBetween(now, then t0.Time) int {
   164  	return int(math.Trunc(now.Sub(then).Hours() / 24 / ApproxDaysPerMonth))
   165  }
   166  
   167  func DaysBetween(now, then t0.Time) int {
   168  	return int(math.Trunc(now.Sub(then).Hours() / 24))
   169  }
   170  
   171  func HoursBetween(now, then t0.Time) int {
   172  	return int(math.Trunc(now.Sub(then).Hours()))
   173  }
   174  
   175  func MinutesBetween(now, then t0.Time) int {
   176  	return int(math.Trunc(now.Sub(then).Minutes()))
   177  }
   178  
   179  func SecondsBetween(now, then t0.Time) int {
   180  	return int(math.Trunc(now.Sub(then).Seconds()))
   181  }
   182  
   183  func MilliSecondsBetween(now, then t0.Time) int64 {
   184  	return now.Sub(then).Milliseconds()
   185  }
   186  
   187  func WithInPastYears(now, then t0.Time, years int) bool {
   188  	return YearsBetween(now, then) <= years
   189  }
   190  
   191  func WithInPastMonths(now, then t0.Time, months int) bool {
   192  	return MonthsBetween(now, then) <= months
   193  }
   194  
   195  func WithInPastDays(now, then t0.Time, days int) bool {
   196  	return DaysBetween(now, then) <= days
   197  }
   198  
   199  func WithInPastHours(now, then t0.Time, hours int) bool {
   200  	return HoursBetween(now, then) <= hours
   201  }
   202  
   203  func WithInPastMinutes(now, then t0.Time, minutes int) bool {
   204  	return MinutesBetween(now, then) <= minutes
   205  }
   206  
   207  func WithInPastSeconds(now, then t0.Time, seconds int) bool {
   208  	return SecondsBetween(now, then) <= seconds
   209  }
   210  
   211  func WithInPastMilliSeconds(now, then t0.Time, milliSeconds int64) bool {
   212  	return MilliSecondsBetween(now, then) <= milliSeconds
   213  }
   214  
   215  func YearSpan(now, then t0.Time) float64 {
   216  	return now.Sub(then).Hours() / 24 / ApproxDaysPerYear
   217  }
   218  
   219  func MonthSpan(now, then t0.Time) float64 {
   220  	return now.Sub(then).Hours() / 24 / ApproxDaysPerMonth
   221  }
   222  
   223  func DaySpan(now, then t0.Time) float64 {
   224  	return now.Sub(then).Hours() / 24
   225  }
   226  
   227  func HourSpan(now, then t0.Time) float64 {
   228  	return now.Sub(then).Hours()
   229  }
   230  
   231  func MinuteSpan(now, then t0.Time) float64 {
   232  	return now.Sub(then).Minutes()
   233  }
   234  
   235  func SecondSpan(now, then t0.Time) float64 {
   236  	return now.Sub(then).Seconds()
   237  }
   238  
   239  func MilliSecondSpan(now, then t0.Time) int64 {
   240  	return now.Sub(then).Milliseconds()
   241  }
   242  
   243  func Now() t0.Time {
   244  	return t0.Now()
   245  }
   246  
   247  func AddHour(times t0.Time, plusOrMinus string, seconds string) t0.Time {
   248  	h, _ := t0.ParseDuration(fmt.Sprintf("%s%v", plusOrMinus, seconds))
   249  	return times.Add(h)
   250  }
   251  
   252  func AddMinutes(times t0.Time, plusOrMinus string, minutes string) t0.Time {
   253  	h, _ := t0.ParseDuration(fmt.Sprintf("%s%v", plusOrMinus, minutes))
   254  	return times.Add(h)
   255  }
   256  
   257  func AddSeconds(times t0.Time, plusOrMinus string, hours string) t0.Time {
   258  	h, _ := t0.ParseDuration(fmt.Sprintf("%s%v", plusOrMinus, hours))
   259  	return times.Add(h)
   260  }
   261  
   262  func AddDays(times t0.Time, days int) t0.Time {
   263  	return times.AddDate(0, 0, days)
   264  }
   265  
   266  func AddMonths(times t0.Time, month int) t0.Time {
   267  	return times.AddDate(0, month, 0)
   268  }
   269  
   270  func AddYears(times t0.Time, year int) t0.Time {
   271  	return times.AddDate(year, 0, 0)
   272  }
   273  
   274  func ParseTime(timeStr string) t0.Time {
   275  	timeStr = strings.TrimSpace(timeStr)
   276  	timeStr = strings.TrimSpace(strings.ReplaceAll(timeStr, "\\'", " "))
   277  
   278  	if timeStr == "" {
   279  		return EmptyTime
   280  	}
   281  	if yRegex.MatchString(timeStr) {
   282  		if times, err := t0.Parse(FmtY, timeStr); err == nil {
   283  			return times
   284  		} else {
   285  			log.Printf("解析时间错误, err: %v", err)
   286  		}
   287  	} else if yyyyMmDdRegex.MatchString(timeStr) {
   288  		if times, err := t0.Parse(FmtYYYYMMdd, timeStr); err == nil {
   289  			return times
   290  		} else {
   291  			log.Printf("解析时间错误, err: %v", err)
   292  		}
   293  	} else if ymRegex.MatchString(timeStr) {
   294  		if times, err := t0.Parse(FmtYM, timeStr); err == nil {
   295  			return times
   296  		} else {
   297  			log.Printf("解析时间错误, err: %v", err)
   298  		}
   299  	} else if ymdRegex.MatchString(timeStr) {
   300  		if times, err := t0.Parse(FmtYMd, timeStr); err == nil {
   301  			return times
   302  		} else {
   303  			log.Printf("解析时间错误, err: %v", err)
   304  		}
   305  	} else if ymdHRegex.MatchString(timeStr) {
   306  		if times, err := t0.Parse(FmtYMdH, timeStr); err == nil {
   307  			return times
   308  		} else {
   309  			log.Printf("解析时间错误, err: %v", err)
   310  		}
   311  	} else if ymdHmRegex.MatchString(timeStr) {
   312  		if times, err := t0.Parse(FmtYMdHm, timeStr); err == nil {
   313  			return times
   314  		} else {
   315  			log.Printf("解析时间错误, err: %v", err)
   316  		}
   317  	} else if ymdHmsRegex.MatchString(timeStr) {
   318  		if times, err := t0.Parse(FmtYMdHms, timeStr); err == nil {
   319  			return times
   320  		} else {
   321  			log.Printf("解析时间错误, err: %v", err)
   322  		}
   323  	} else if ymdHmsSRegex.MatchString(timeStr) {
   324  		if times, err := t0.Parse(FmtYMdHmsSSS, timeStr); err == nil {
   325  			return times
   326  		} else {
   327  			log.Printf("解析时间错误, err: %v", err)
   328  		}
   329  	} else {
   330  		log.Printf("解析时间错误, time: %v", timeStr)
   331  	}
   332  	return EmptyTime
   333  }
   334  
   335  func IsTimeEmpty(time t0.Time) bool {
   336  	return time == EmptyTime
   337  }
   338  
   339  func NumToTimeDuration(num int, duration t0.Duration) t0.Duration {
   340  	int64Num, _ := strconv.ParseInt(fmt.Sprintf("%v", num), 10, 64)
   341  	return t0.Duration(int64Num * duration.Nanoseconds())
   342  }