sql.NullTime 计算时间差

更新日期: 2021-10-12 阅读次数: 4679 字数: 278 分类: golang

定了一个类型,实际上是 sql.NullTime。我想计算当前时间与其值的时间差。

type NullTime struct {
	sql.NullTime
}

sql.NullTime

https://pkg.go.dev/database/sql#NullTime

type NullTime struct {
	Time  time.Time
	Valid bool // Valid is true if Time is not NULL
}

NullTime 实际上是个 struct,时间值存储在 Time 字段中。

time.Time 如何计算时间差

https://stackoverflow.com/questions/40260599/difference-between-two-time-time-objects

计算两个 time.Time 类型的时间差,可以使用 Time.Sub(),返回的值类型为 time.Duration。

而 time.Duration 是一个 int64 类型,代表 nanosecond 纳秒,最大可表示 290 年。

type Duration int64

纳秒

秒 > 毫秒 > 微妙 > 纳秒 (十亿分之一秒)

time.go 中,可以看到如下定义:

const (
	Nanosecond  Duration = 1
	Microsecond          = 1000 * Nanosecond
	Millisecond          = 1000 * Microsecond
	Second               = 1000 * Millisecond
	Minute               = 60 * Second
	Hour                 = 60 * Minute
)

Time.Sub 测试代码

package main

import (
	"fmt"
	"time"
)

func main() {
	t1 := time.Now()
	time.Sleep(time.Millisecond * 6000)
	t2 := time.Now()

	diff := t2.Sub(t1)
	fmt.Println(diff)      // 6.0006926s
	fmt.Printf("%d", diff) // 6001581900
}

所以,只需要对 NullTime.Time 进行比对即可。

为何直接打印 Duration 显示的是字符串

time.go 中定义了一个 String 函数。

// String returns a string representing the duration in the form "72h3m0.5s".
func (d Duration) String() string {
	// Largest time is 2540400h10m10.000000000s
	var buf [32]byte
	...
}

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式