日期格式转换
将时间字符串转时间戳 str to timestamp
time.ParseInLocation
// 将时间字符串转换为时间戳 (本地实际)
func Str2Time(timeStr string) time.Time {
timeTpl := "2006-01-02 15:04:05"
t, _ := time.ParseInLocation(timeTpl, timeStr, time.Local)
return t
}
温故而知新:
time.local是怎样实现的?
// Local represents the system's local time zone.
// On Unix systems, Local consults the TZ environment
// variable to find the time zone to use. No TZ means
// use the system default /etc/localtime.
// TZ="" means use UTC.
// TZ="foo" means use file foo in the system timezone directory.
var Local *Location = &localLoc
// Local表示系统的本地时区。
//在Unix系统中,Local参考TZ环境
//查找时区的变量。没有TZ意味着
//使用系统默认值/etc/localtime。
// TZ=""表示使用UTC。
// TZ="foo"表示使用系统时区目录下的foo文件
时间戳转时间字符串 timestamp to str
time.Unix(timestamp,0).Format(timeTpl)
func Time2String(t int64) string {
tm := time.Unix(t, 0)
return tm.Format("2006-01-02 15:04:05")
}
time.Unix,里面有个两个参数,第一个参数是:sec,秒的意思,传秒级别的时间戳;第二个参数是nsec,纳秒级的意思,传纳秒级别的时间戳。两个参数如果只用一个,另一个传0,这个函数的意义就是,将秒级时间戳转化为time对象或者将纳秒级别时间戳转化为time对象,这种用法比较多。
如果两个参数都上了,就是两个数相加的时间戳在转化为time,用得比较少。
其实都是先转化为time对象,再根据time对象的方法进行转换。
再说一个对日期的加减,这个也比较常用:
time.Now().AddDate(1,2,3)
意思就是:当前时间+1年2个月3天
开发时可能需要求下个月的今天为截止时间:
time.Now().AddDate(0,1,0)
十分的牛!