golang的time包:时间字符串和时间戳的相互转换

本博客转自: https://blog.csdn.net/mirage003/article/details/86073046

package main

import (
	"log"
	"time"
)

func main() {
	t := int64(1546926630)      //外部传入的时间戳(秒为单位),必须为int64类型
	t1 := "2019-01-08 13:50:30" //外部传入的时间字符串

	//时间转换的模板,golang里面只能是 "2006-01-02 15:04:05" (go的诞生时间)
	timeTemplate1 := "2006-01-02 15:04:05" //常规类型
	timeTemplate2 := "2006/01/02 15:04:05" //其他类型
	timeTemplate3 := "2006-01-02"          //其他类型
	timeTemplate4 := "15:04:05"            //其他类型

	// ======= 将时间戳格式化为日期字符串 =======
	log.Println(time.Unix(t, 0).Format(timeTemplate1)) //输出:2019-01-08 13:50:30
	log.Println(time.Unix(t, 0).Format(timeTemplate2)) //输出:2019/01/08 13:50:30
	log.Println(time.Unix(t, 0).Format(timeTemplate3)) //输出:2019-01-08
	log.Println(time.Unix(t, 0).Format(timeTemplate4)) //输出:13:50:30

	// ======= 将时间字符串转换为时间戳 =======
	stamp, _ := time.ParseInLocation(timeTemplate1, t1, time.Local) //使用parseInLocation将字符串格式化返回本地时区时间
	log.Println(stamp.Unix())  //输出:1546926630
}

package main

import (
	"log"
	"time"
)
func main(){
    // 获取每天的零点时间戳, 一个小时的时间戳是3600
    timeStr := time.Now().Format("2006-01-02")
    t, _ := time.ParseInLocation("2006-01-02", timeStr, time.Local)
    timeUnix := t.Unix()
}
package main

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

func main() {
    t := time.Now()
    fmt.Println(t)

    fmt.Println(t.UTC().Format(time.UnixDate))

    fmt.Println(t.Unix())

    timestamp := strconv.FormatInt(t.UTC().UnixNano(), 10)
    fmt.Println(timestamp)
    timestamp = timestamp[:10]
    fmt.Println(timestamp)
}

//输出: 
//2019-09-02 19:17:58.2508394 +0800 CST m=+0.001994001
//Mon Sep  2 11:17:58 UTC 2019
//1567423078
//1567423078250839400
//1567423078
package main

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

func main() {
    const longForm = "Jan 2, 2006 at 3:04pm (MST)"
    t, _ := time.Parse(longForm, "Jun 21, 2017 at 0:00am (PST)")
    fmt.Println(t)

    const shortForm = "2006-Jan-02"
    t, _ = time.Parse(shortForm, "2017-Jun-21")
    fmt.Println(t)

    t, _ = time.Parse("01/02/2006", "06/21/2017")
    fmt.Println(t)
    fmt.Println(t.Unix())

    i, err := strconv.ParseInt("1498003200", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm)

    var timestamp int64 = 1498003200
    tm2 := time.Unix(timestamp, 0)
    fmt.Println(tm2.Format("2006-01-02 03:04:05 PM"))
    fmt.Println(tm2.Format("02/01/2006 15:04:05 PM"))
}

//输出
//2017-06-21 00:00:00 +0000 PST
//2017-06-21 00:00:00 +0000 UTC
//2017-06-21 00:00:00 +0000 UTC
//1498003200
//2017-06-21 08:00:00 +0800 CST
//2017-06-21 08:00:00 AM
//21/06/2017 08:00:00 AM
time常用方法

After(u Time) bool 
时间类型比较,是否在Time之后

Before(u Time) bool 
时间类型比较,是否在Time之前

Equal(u Time) bool 
比较两个时间是否相等

IsZero() bool 
判断时间是否为零值,如果sec和nsec两个属性都是0的话,则该时间类型为0

Date() (year int, month Month, day int) 
返回年月日,三个参数

Year() int 
返回年份

Month() Month 
返回月份.是Month类型

Day() int 
返回多少号

Weekday() Weekday 
返回星期几,是Weekday类型

ISOWeek() (year, week int) 
返回年份,和该填是在这年的第几周.

Clock() (hour, min, sec int) 
返回小时,分钟,秒

Hour() int 
返回小时

Minute() int 
返回分钟

Second() int 
返回秒数

Nanosecond() int 
返回纳秒

计算时间差

package main

import (
	"fmt"
	"strings"
	"time"
)

func main() {
	// Add 时间相加
	now := time.Now()
	// ParseDuration parses a duration string.
	// A duration string is a possibly signed sequence of decimal numbers,
	// each with optional fraction and a unit suffix,
	// such as "300ms", "-1.5h" or "2h45m".
	//  Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
	// 10分钟前
	m, _ := time.ParseDuration("-1m")
	m1 := now.Add(m)
	fmt.Println(m1)

	// 8个小时前
	h, _ := time.ParseDuration("-1h")
	h1 := now.Add(8 * h)
	fmt.Println(h1)

	// 一天前
	d, _ := time.ParseDuration("-24h")
	d1 := now.Add(d)
	fmt.Println(d1)

	printSplit(50)

	// 10分钟后
	mm, _ := time.ParseDuration("1m")
	mm1 := now.Add(mm)
	fmt.Println(mm1)

	// 8小时后
	hh, _ := time.ParseDuration("1h")
	hh1 := now.Add(hh)
	fmt.Println(hh1)

	// 一天后
	dd, _ := time.ParseDuration("24h")
	dd1 := now.Add(dd)
	fmt.Println(dd1)

	printSplit(50)

	// Sub 计算两个时间差
	subM := now.Sub(m1)
	fmt.Println(subM.Minutes(), "分钟")

	sumH := now.Sub(h1)
	fmt.Println(sumH.Hours(), "小时")

	sumD := now.Sub(d1)
	fmt.Printf("%v 天\n", sumD.Hours()/24)

}

func printSplit(count int) {
	fmt.Println(strings.Repeat("#", count))
}
posted @   xushukui  阅读(70683)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示