Go对时间类型的处理

  • Post author:
  • Post category:其他



提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档




前言



一、datetime转换成时间字符串

Format函数

package main
 
import (
    "fmt"
    "reflect"
    "time"
)
 
func main() {
    now := time.Now()       // 当前 datetime 时间
    fmt.Println(reflect.TypeOf(now))    // 打印当前时间的类型
    fmt.Println(now)        // 打印当前时间
    fmt.Println("***********************")
    t1 := now.Format("2006-01-02 15:04:05")     // 把当前 datetime 时间转换成时间字符串
    fmt.Println(t1)
    fmt.Println(reflect.TypeOf(t1))
}


执行结果

time.Time
2019-09-16 17:51:01.2357834 +0800 CST m=+0.004988701
***********************
2019-09-16 17:51:01
string



二、datetime转换成时间戳

package main
 
import (
    "fmt"
    "time"
)
 
func parse_datetime_to_timestamp(d time.Time) int64 {
    unix_time := d.Unix()
    return unix_time
}
func main() {
    now := time.Now()                      // 当前 datetime 时间
    t1 := parse_datetime_to_timestamp(now) // 转换成时间戳
 
    tomorrow := now.AddDate(0, 0, +1)           // 一天之后的 datetime 时间
    t2 := parse_datetime_to_timestamp(tomorrow) // 转换成时间戳
 
    fmt.Println(t1)
    fmt.Println(t2)
}


执行结果

1568631868
1568718268



三、字符串时间转换成时间搓

//字符串类型转换成时间类型
time.Parse("2006010215:04", "2022012215:30")

//时间类型转换成时间搓
func parse_datetime_to_timestamp(d time.Time) int64 {
	unix_time := d.Unix()
	return unix_time
}

func main() {
	tm, _ := time.Parse("2006010215:04", "2022012215:30")
	
	res := parse_datetime_to_timestamp(tm)
	res = res - 8*60*60   //东八区时间要减去8小时
	fmt.Println(res)
}



四、日期加减操作

package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    now := time.Now()       // 当前 datetime时间
    tomorrow := now.AddDate(0, 0, +1)   // 一天之后的时间
    fmt.Println(tomorrow)
    
    day_after_15 := now.AddDate(0, 0, -15)  // 15天之前的时间
    fmt.Println(day_after_15)
}

执行结果

2019-09-17 17:55:59.4755575 +0800 CST
2019-09-01 17:55:59.4755575 +0800 CST



五、时间搓转换成格式字符串

time.Unix(successTime, 0).Format("Jan 02 2006, 15:04 PM"),



版权声明:本文为chenhongxun1原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。