Duration Unit Conversion Milliseconds

Show that time.Duration(1500) means 1500 nanoseconds, not milliseconds: untyped integer conversions silently shrink durations by three orders of magnitude.

GoData Integrity

Code

gosnippet
23 lines
package main

import (
	"fmt"
	"time"
)

func main() {
	// 配置文件里写的是毫秒 milliseconds 数
	ms := 1500

	// 错误:整型直接转 Duration,单位是纳秒(unit conversion 陷阱)
	wrong := time.Duration(ms)
	fmt.Println("wrong:", wrong)

	// 正确:乘上单位常量 time.Millisecond 才是 1.5 秒
	right := time.Duration(ms) * time.Millisecond
	fmt.Println("right:", right)

	// 派生 deadline:毫秒值只能以乘过单位的形式进入时间运算
	deadline := time.Now().Add(right)
	fmt.Println("deadline after now:", deadline.After(time.Now()))
}

What the snippet is doing

Duration Unit Conversion Milliseconds reduces to the function main.

Caveats

  • Self-sufficient — imports, if any, go no further than what the runtime ships.

Using it

The primary signature is func main()

The demo output is labeled (wrong:, right:, deadline after now:), so each printed line maps back to the step behind it.

Key statements

right := time.Duration(ms) * time.Millisecond

Interactive Tools for This Topic

FAQ

What does Duration Unit Conversion Milliseconds print when run?
Execute the whole file; each printed line is prefixed with a label like `wrong:`, `right:`, `deadline after now:`.