github.com/searKing/golang/go@v1.2.74/time/convert.go (about)

     1  // Copyright 2022 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package time
     6  
     7  import "time"
     8  
     9  // RatioFrom Example:
    10  // ratio, divide := RatioFrom(fromUnit, toUnit)
    11  // if divide {
    12  //   toDuration = fromDuration / ratio
    13  //   fromDuration = toDuration * ratio
    14  // } else {
    15  //   toDuration = fromDuration * ratio
    16  //   fromDuration = toDuration / ratio
    17  // }
    18  func RatioFrom(from time.Duration, to time.Duration) (ratio time.Duration, divide bool) {
    19  	if from >= to {
    20  		return from / to, false
    21  	}
    22  
    23  	return to / from, true
    24  }
    25  
    26  // ConvertTimestamp convert timestamp from one unit to another unit
    27  func ConvertTimestamp(timestamp int64, from, to time.Duration) int64 {
    28  	ratio, divide := RatioFrom(from, to)
    29  	if divide {
    30  		return int64(time.Duration(timestamp) / ratio)
    31  	}
    32  	return int64(time.Duration(timestamp) * ratio)
    33  }
    34  
    35  // Timestamp returns a Unix timestamp in unit from "January 1, 1970 UTC".
    36  // The result is undefined if the Unix time cannot be represented by an int64.
    37  // Which includes calling TimeUnixMilli on a zero Time is undefined.
    38  //
    39  // See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information.
    40  func Timestamp(t time.Time, unit time.Duration) int64 {
    41  	return ConvertTimestamp(t.UnixNano(), time.Nanosecond, unit)
    42  }
    43  
    44  // UnixWithUnit returns the local Time corresponding to the given Unix time by unit
    45  func UnixWithUnit(timestamp int64, unit time.Duration) time.Time {
    46  	sec := ConvertTimestamp(timestamp, unit, time.Second)
    47  	nsec := time.Duration(timestamp)*unit - time.Duration(sec)*time.Second
    48  	return time.Unix(sec, int64(nsec))
    49  }