github.com/searKing/golang/go@v1.2.117/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  //
    12  //	if divide {
    13  //	  toDuration = fromDuration / ratio
    14  //	  fromDuration = toDuration * ratio
    15  //	} else {
    16  //
    17  //	  toDuration = fromDuration * ratio
    18  //	  fromDuration = toDuration / ratio
    19  //	}
    20  func RatioFrom(from time.Duration, to time.Duration) (ratio time.Duration, divide bool) {
    21  	if from >= to {
    22  		return from / to, false
    23  	}
    24  
    25  	return to / from, true
    26  }
    27  
    28  // ConvertTimestamp convert timestamp from one unit to another unit
    29  func ConvertTimestamp(timestamp int64, from, to time.Duration) int64 {
    30  	ratio, divide := RatioFrom(from, to)
    31  	if divide {
    32  		return int64(time.Duration(timestamp) / ratio)
    33  	}
    34  	return int64(time.Duration(timestamp) * ratio)
    35  }
    36  
    37  // Timestamp returns a Unix timestamp in unit from "January 1, 1970 UTC".
    38  // The result is undefined if the Unix time cannot be represented by an int64.
    39  // Which includes calling TimeUnixMilli on a zero Time is undefined.
    40  //
    41  // See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information.
    42  func Timestamp(t time.Time, unit time.Duration) int64 {
    43  	return ConvertTimestamp(t.UnixNano(), time.Nanosecond, unit)
    44  }
    45  
    46  // UnixWithUnit returns the local Time corresponding to the given Unix time by unit
    47  func UnixWithUnit(timestamp int64, unit time.Duration) time.Time {
    48  	sec := ConvertTimestamp(timestamp, unit, time.Second)
    49  	nsec := time.Duration(timestamp)*unit - time.Duration(sec)*time.Second
    50  	return time.Unix(sec, int64(nsec))
    51  }