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.
Code
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
CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.