GolangNote

Golang笔记

Golang 字符串毫秒转时间格式

Permalink

Golang 字符串毫秒转时间格式

Go: 字符串毫秒转时间格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
	"fmt"
	"strconv"
	"time"
)

func main() {
	fmt.Println(msToTime("1489582166978"))
}

func msToTime(ms string) (time.Time, error) {
	msInt, err := strconv.ParseInt(ms, 10, 64)
	if err != nil {
		return time.Time{}, err
	}

	tm := time.Unix(0, msInt*int64(time.Millisecond))

	fmt.Println(tm.Format("2006-02-01 15:04:05.000"))

	return tm, nil
}

输出:

plaintext: 字符串毫秒转时间格式结果
1
2
2017-15-03 20:49:26.978
2017-03-15 20:49:26.978 +0800 CST <nil>

另外一种(秒):

Go: 字符串秒转时间格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
	"fmt"
	"strconv"
	"time"
)

func main() {
	i, err := strconv.ParseInt("1489582166", 10, 64)
	if err != nil {
		panic(err)
	}
	tm := time.Unix(i, 0)
	fmt.Println(tm)
	fmt.Println(tm.Format("2006-02-01 15:04:05"))
}

// 2017-03-15 20:49:26 +0800 CST
// 2017-15-03 20:49:26

  • 10位数的时间戳是以 秒 为单位
  • 13位数的时间戳是以 毫秒 为单位
  • 19位数的时间戳是以 纳秒 为单位

Go: 常用时间
1
2
3
4
fmt.Printf("时间戳(秒):%v;\n", time.Now().Unix())
fmt.Printf("时间戳(纳秒):%v;\n",time.Now().UnixNano())
fmt.Printf("时间戳(毫秒):%v;\n",time.Now().UnixNano() / 1e6)
fmt.Printf("时间戳(纳秒转换为秒):%v;\n",time.Now().UnixNano() / 1e9)

本文网址: https://golangnote.com/topic/156.html 转摘请注明来源

Related articles

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

Write a Comment to "Golang 字符串毫秒转时间格式"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms