github.com/go-chrono/chrono@v0.0.0-20240102183611-532f0d0d7c34/time.go (about)

     1  package chrono
     2  
     3  import "fmt"
     4  
     5  const (
     6  	oneHour   = int64(Hour)
     7  	oneMinute = int64(Minute)
     8  	oneSecond = int64(Second)
     9  
    10  	maxTime int64 = 359999999999999
    11  )
    12  
    13  func makeTime(hour, min, sec, nsec int) (int64, error) {
    14  	if hour < 0 || hour > 99 || min < 0 || min > 59 || sec < 0 || sec > 59 || nsec < 0 || nsec > 999999999 {
    15  		return 0, fmt.Errorf("invalid time")
    16  	}
    17  
    18  	h, m, s, n := int64(hour), int64(min), int64(sec), int64(nsec)
    19  	return h*oneHour + m*oneMinute + s*oneSecond + n, nil
    20  }
    21  
    22  func fromTime(v int64) (hour, min, sec, nsec int) {
    23  	nsec = int(v) % int(oneSecond)
    24  	sec = int(v) / int(oneSecond)
    25  
    26  	hour = (sec / (60 * 60)) % 24
    27  	sec -= hour * (60 * 60)
    28  
    29  	min = sec / 60
    30  	sec -= min * 60
    31  	return
    32  }
    33  
    34  func addTime(t, v int64) (int64, error) {
    35  	if v > maxTime {
    36  		return 0, fmt.Errorf("invalid duration v")
    37  	}
    38  
    39  	out := t + v
    40  	if out > int64(maxTime) {
    41  		return 0, fmt.Errorf("invalid time t+v")
    42  	}
    43  
    44  	if out < 0 {
    45  		return 24*oneHour + (out % (24 * oneHour)), nil
    46  	}
    47  	return out, nil
    48  }
    49  
    50  func simpleTimeStr(hour, min, sec, nsec int, offset *int64) string {
    51  	out := fmt.Sprintf("%02d:%02d:%02d", hour, min, sec)
    52  	if nsec != 0 {
    53  		out += fmt.Sprintf(".%09d", nsec)
    54  	}
    55  
    56  	if offset == nil {
    57  		return out
    58  	}
    59  	return out + offsetString(*offset, ":")
    60  }
    61  
    62  func timeBusinessHour(t int64) int {
    63  	return int(t / oneHour)
    64  }
    65  
    66  func timeNanoseconds(t int64) int {
    67  	return int(t % oneSecond)
    68  }
    69  
    70  func compareTimes(t, t2 int64) int {
    71  	switch {
    72  	case t < t2:
    73  		return -1
    74  	case t > t2:
    75  		return 1
    76  	default:
    77  		return 0
    78  	}
    79  }