golang时间字符串和时间戳转换
2017-12-29 16:18
357 查看
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. 获取当天零点时间戳
方法1package 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. */
参考
官方文档:The Go Programming Language-Package time相关文章推荐
- golang日期字符串与时间戳转换
- golang获取当前时间、时间戳和时间字符串及它们之间的相互转换
- 把字符串转换成时间格式或日期格式
- 关于Python中时间与字符串直接的转换...
- 关于java将String类型的时间字符串转换为Date类型的问题
- C++ Builder 字符串时间格式转换为TDateTime方法
- java工具类——字符串类型的时间格式转换为Timestamp类型
- Java字符串转换为日期和时间比较大小
- SQL Server日期时间格式转换字符串详解
- iOS ISO8601格式的时间日期字符串转换成NSDate
- IOS将字符串转换为日期时间格式
- 提供两个字符串与时间格式COleDateTime的转换
- 【Code】时间戳转换天时分秒字符串
- js将字符串时间格式yyyy-MM-dd hh:mm:ss 转换为long
- js获取时间并实现字符串和时间戳之间的转换
- java计时中字符串时间与秒的转换
- SQL 时间类型与字符串类型相互转换
- python_12(查找字符串、字符串查找、时间转换、正则、限定符、分组)
- Java字符串转换为日期和时间比较大小
- javascript时间戳和日期字符串相互转换