Go语言时间格式化
2017-04-17 17:22
821 查看
package main import ( "fmt" "time" ) func main() { fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // -->2017-04-17 17:21:33 fmt.Println(timFormat("2017-12-24 23", "yyyy-MM-dd HH:mm:ss")) // -->2017-12-24 23:00:00 } /* 将输入的date按照指定的partten格式化 @version 1.0 目前只支持正常的格式,其余变态格式暂不支持 如:yyyy,yyyy-MM,yyyy-MM-dd,yyyy-MM-dd HH,yyyy-MM-dd HH:mm,yyyy-MM-dd HH:mm:ss @date string 要被格式化的日期 @partten stirng 指定格式 @author wangdy return 返回格式化后的日期 */ func timFormat(date, partten string) string { var ptnLength = len(partten) var dateLength = len(date) returnStr := date switch partten { case partten: if ptnLength <= dateLength { return Substr(date, 0, ptnLength) } else { var chaLen = ptnLength - dateLength if dateLength == 4 { if chaLen == 3 { returnStr += "-01" return returnStr } else if chaLen == 6 { returnStr += "-01-01" return returnStr } else if chaLen == 9 { returnStr += "-01-01 00" return returnStr } else if chaLen == 12 { returnStr += "-01-01 00:00" return returnStr } else if chaLen == 15 { returnStr += "-01-01 00:00:00" return returnStr } } else if dateLength == 7 { if chaLen == 3 { returnStr += "-01" return returnStr } else if chaLen == 6 { returnStr += "-01 00" return returnStr } else if chaLen == 9 { returnStr += "-01 00:00" return returnStr } else if chaLen == 12 { returnStr += "-01 00:00:00" return returnStr } } else if dateLength == 10 { if chaLen == 3 { returnStr += " 00" return returnStr } else if chaLen == 6 { returnStr += " 00:00" return returnStr } else if chaLen == 9 { returnStr += " 00:00:00" return returnStr } } else if dateLength == 13 { if chaLen == 3 { returnStr += ":00" return returnStr } else if chaLen == 6 { returnStr += ":00:00" return returnStr } } else if dateLength == 16 && chaLen == 3 { returnStr += ":00" return returnStr } return "xxxxxxxxxx" + date } default: fmt.Println("it's default case!") return date } } /* 按照格式截取字符串 @str string 要被截取的源字符串 @start int 开始索引,从0开始 @length int 要截取的长度 @author wangdy return 返回截取后字符串 */ func Substr(str string, start, length int) string { rs := []rune(str) rl := len(rs) end := 0 if start < 0 { start = rl - 1 + start } end = start + length if start > end { start, end = end, start } if start < 0 { start = 0 } if start > rl { start = rl } if end < 0 { end = 0 } if end > rl { end = rl } return string(rs[start:end]) }
以上就是datetime的格式化方法了。可能不是最优代码,如有特别好的建议,请评论,或者发邮箱wdy2099@126.ccom.
相关文章推荐
- go语言中时间戳格式化的方法
- Go 语言中格式化时间
- GO语言时间格式化,奇葩得不想说了
- Django模版语言 格式化显示 后台datatime()时间
- 多语言环境下,使用SimpleDateFormat格式化时间字符串的时候,不能正确显示阿拉伯数字
- 七牛的时间戳防盗链go语言
- go语言计算两个时间的时间差
- Go 语言——字符串、数据的格式化输出(Printf)
- go语言里时间相加,在一个时间段里加几天
- Go语言 北京UTC+8 时间问题
- iOS 开发中的一些注意点(安全、当前语言、时间格式化)
- go语言计算两个时间的时间差方法
- go语言计算两个时间的时间差方法
- Go语言技巧:使用for range time.Tick()固定间隔时间执行
- C语言时间函数time_t格式化打印...
- Android 在12,24小时制,以及不同语言下日期和时间的格式化
- go time Format 格式化时间的使用
- Go语言_时间篇
- go 语言中 日期转换 日期、时间戳、字符串 的转换(这个是最终答案)
- 在go语言中统计程序执行时间