1. 程式人生 > 實用技巧 >go的時間相關

go的時間相關

package main

import (
	"fmt"
	"time"
)

func main() {
	GetCTimeToString()
	FromYourIntToTime()
	GetTimeStamp()
	TimeStampToTime()
	CalculateTime()
}

/*
獲取當前時間,並轉化為字串
*/
func GetCTimeToString() {
	var currentTime = time.Now()
	cStr := currentTime.Format("2006-01-02 15:04:05")
	fmt.Printf("local current time : %s\n", cStr)
	fmt.Printf("local current time Yeer: %d\n", currentTime.Year())
	fmt.Printf("local current time Month: %d\n", currentTime.Month())
	fmt.Printf("local current time Day: %d\n", currentTime.Day())
	fmt.Printf("local current time Hour: %d\n", currentTime.Hour())
	fmt.Printf("local current time Minute: %d\n", currentTime.Minute())
	fmt.Printf("local current time Second: %d\n", currentTime.Second())
	fmt.Printf("local current time Second: %d\n", currentTime.Second())
	fmt.Printf("local current time Weekday: %d\n", currentTime.Weekday())
}

/*
將資料轉化為時間
*/
func FromYourIntToTime() {
	var year int = 1992
	var month time.Month = 6
	var day int = 27
	var hour int = 13
	var min int = 33
	var sec int = 48
	var nsec int = 0
	zone, err := time.LoadLocation("Asia/ShangHai")
	if err != nil {
		panic(err.Error())
	}
	dateTime := time.Date(year, month, day, hour, min, sec, nsec, zone)
	fmt.Println(dateTime)

	// 第二種方式:
	stringTime := "1992-06-27 13:33:48"
	loc, _ := time.LoadLocation("Local")
	the_time, err := time.ParseInLocation("2006-01-02 15:04:05", stringTime, loc)
	if err != nil {
		panic(err.Error())
	}
	fmt.Println(the_time)
}

func GetTimeStamp() {
	TimeStamp := time.Now().Unix()
	TimeStampn := time.Now().UnixNano()
	fmt.Println(TimeStamp, TimeStampn)
}

func TimeStampToTime() {
	TimeStamp := time.Now().Unix()
	timeC := time.Unix(TimeStamp, 0)
	timeString := timeC.Format("2006-01-02 15:04:05")
	fmt.Println(timeString)
}

func CalculateTime() {
	// 需要一個時間物件
	now := time.Now()
	fmt.Println(now.Format("2006-01-02 15:04:05"))
	// 往前算
	m, _ := time.ParseDuration("-1m") // 1分鐘之前
	m1 := now.Add(m)
	fmt.Println(m1.Format("2006-01-02 15:04:05"))

	d, _ := time.ParseDuration("-24h") // 1填之前
	d1 := now.Add(d)
	fmt.Println(d1.Format("2006-01-02 15:04:05"))

	d3, _ := time.ParseDuration("-24h") // 3填之前
	d3d := now.Add(d3 * 3)
	fmt.Println(d3d.Format("2006-01-02 15:04:05"))
	//之後
	fmt.Println("---------")
	fmt.Println(now.Format("2006-01-02 15:04:05"))
	// 往前算
	mm, _ := time.ParseDuration("1m") // 1分鐘之後
	m1m := now.Add(mm)
	fmt.Println(m1m.Format("2006-01-02 15:04:05"))

	dd, _ := time.ParseDuration("24h") // 1填之後
	d1d := now.Add(dd)
	fmt.Println(d1d.Format("2006-01-02 15:04:05"))

	d3dd, _ := time.ParseDuration("24h")
	dd3 := now.Add(d3dd * 3) // 3填之後
	fmt.Println(dd3.Format("2006-01-02 15:04:05"))

}