github.com/chain5j/chain5j-pkg@v1.0.7/util/dateutil/time.go (about)

     1  // Package dateutil
     2  // @author: xwc1125
     3  package dateutil
     4  
     5  import (
     6  	"fmt"
     7  	"strings"
     8  	"time"
     9  )
    10  
    11  // DiffNano 时间差,纳秒
    12  func DiffNano(startTime time.Time) (diff int64) {
    13  	startTimeStamp := startTime.UnixNano()
    14  	endTimeStamp := time.Now().UnixNano()
    15  
    16  	diff = endTimeStamp - startTimeStamp
    17  	return
    18  }
    19  
    20  // GetDistanceTimeToCurrent 传入的是毫秒值
    21  func GetDistanceTimeToCurrent(startTime int64) string {
    22  	diff := CurrentTime() - startTime
    23  	return GetDistanceTime(diff)
    24  }
    25  
    26  // GetDistanceTime 获取间隔时间错,传入的是毫秒
    27  func GetDistanceTime(diffMS int64) string {
    28  	isNegative := false
    29  	if diffMS < 0 {
    30  		isNegative = true
    31  		diffMS = -diffMS
    32  	}
    33  	s := diffMS / 1000 // 秒
    34  	m := s / 60        // 分钟
    35  	h := m / 60        // 小时
    36  	day := h / 24      // 天
    37  	hour := h - 24*day
    38  	min := m - h*60
    39  	sec := s - m*60
    40  	ms := diffMS - s*1000
    41  	var buff strings.Builder
    42  	if isNegative {
    43  		buff.WriteString("-")
    44  	}
    45  	if day > 0 {
    46  		buff.WriteString(fmt.Sprintf("%dd", day))
    47  	}
    48  	if hour > 0 {
    49  		buff.WriteString(fmt.Sprintf("%dh", hour))
    50  	}
    51  	if min > 0 {
    52  		buff.WriteString(fmt.Sprintf("%dm", min))
    53  	}
    54  	if sec > 0 {
    55  		buff.WriteString(fmt.Sprintf("%ds", sec))
    56  	}
    57  	if ms > 0 {
    58  		buff.WriteString(fmt.Sprintf("%dms", ms))
    59  	}
    60  	return buff.String()
    61  }