golang时间字符串和时间戳转换的案例
程序员文章站
2022-03-29 21:33:03
1. 获取当前时间字符串和时间戳package mainimport ( "fmt" "time")func main() { now := time.now().utc() // 显示时间格...
1. 获取当前时间字符串和时间戳
package main import ( "fmt" "time" ) func main() { now := time.now().utc() // 显示时间格式: unixdate = "mon jan _2 15:04:05 mst 2006" fmt.printf("%s\n", now.format(time.unixdate)) // 显示时间戳 fmt.printf("%ld\n", now.unix()) // 显示时分:kitchen = "3:04pm" fmt.printf("%s\n", now.format("3:04pm")) }
更多时间格式
const ( ansic = "mon jan _2 15:04:05 2006" unixdate = "mon jan _2 15:04:05 mst 2006" rubydate = "mon jan 02 15:04:05 -0700 2006" rfc822 = "02 jan 06 15:04 mst" rfc822z = "02 jan 06 15:04 -0700" // rfc822 with numeric zone rfc850 = "monday, 02-jan-06 15:04:05 mst" rfc1123 = "mon, 02 jan 2006 15:04:05 mst" rfc1123z = "mon, 02 jan 2006 15:04:05 -0700" // rfc1123 with numeric zone rfc3339 = "2006-01-02t15:04:05z07:00" rfc3339nano = "2006-01-02t15:04:05.999999999z07:00" kitchen = "3:04pm" // handy time stamps. stamp = "jan _2 15:04:05" stampmilli = "jan _2 15:04:05.000" stampmicro = "jan _2 15:04:05.000000" stampnano = "jan _2 15:04:05.000000000" )
2. 时间字符串解析成时间格式
package main import ( "fmt" "time" ) func main() { timestr := "2018-01-01" fmt.println("timestr:", timestr) t, _ := time.parse("2006-01-02", timestr) fmt.println(t.format(time.unixdate)) }
3. 获取当天零点时间戳
方法1
package main import ( "fmt" "time" ) func main() { timestr := time.now().format("2006-01-02") t, _ := time.parse("2006-01-02", timestr) fmt.println(t.format(time.unixdate)) //unix返回早八点的时间戳,减去8个小时 timestamp := t.utc().unix() - 8*3600 fmt.println("timestamp:", timestamp) }
方法2
package main import ( "fmt" "time" ) func main() { now := time.now() t, _ := time.parseinlocation("2006-01-02", now.format("2006-01-02"), time.local) timestamp := t.unix() fmt.println(timestamp) } /* time.local本地时区 var local *location = &localloc 以及utc时区 var utc *location = &utcloc 还可以替换成指定时区 //func loadlocation(name string) (*location, error) loc, _ := time.loadlocation("europe/berlin") if the name is "" or "utc", loadlocation returns utc. if the name is "local", loadlocation returns local. */
补充:golang中获取当天0点的格式化时间
如下所示:
enddatelimit := time.now().format("2006-01-02 00:00:00")
取当天某个整点的时间戳
now := time.now().unix() muteendtime := time.date(time.now().year(), time.now().month(), time.now().day(), 8, 0, 0, 0, time.local).unix() mutestarttime := time.date(time.now().year(), time.now().month(), time.now().day(), 22, 0, 0, 0, time.local).unix()
本地当前时间戳(10位)
fmt.println(time.now().unix()) //1468479251
本地当前时间戳(19位)
fmt.println(time.now().unixnano()) //1468480006774460462
时间戳转时间
fmt.println(time.unix(1389058332, 0).format("2006-01-02 15:04:05")) //2014-01-07 09:32:12
时间转时间戳
fmt.println(time.date(2014, 1, 7, 5, 50, 4, 0, time.local).unix())
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
上一篇: 逗B笑段,乐翻天呀!
下一篇: 爆逗男女,每对都让人笑半天