Go语言格式化时间

前两天看Go的时间格式化,地址在这里:http://pauladamsmith.com/blog/2011/05/go_time.html,感觉似懂非懂,而且跟java的时间格式化完全不同,所以,自己就动手写了个格式化。

time.go


package utils

import (
"strconv"
"strings"
"time"
)

//format time like java, such as: yyyy-MM-dd HH:mm:ss

func Format(t time.Time, format string) string {

//year
if strings.ContainsAny(format, "y") {

year := strconv.Itoa(t.Year())

if strings.Count(format, "yy") == 1 && strings.Count(format, "y") == 2 {
format = strings.Replace(format, "yy", year[2:], 1)
} else if strings.Count(format, "yyyy") == 1 && strings.Count(format, "y") == 4 {
format = strings.Replace(format, "yyyy", year, 1)
} else {
panic("format year error! please 'yyyy' or 'yy'")
}
}

//month
if strings.ContainsAny(format, "M") {

var month string

if int(t.Month()) < 10 {
month = "0" + strconv.Itoa(int(t.Month()))
} else {
month = strconv.Itoa(int(t.Month()))
}

if strings.Count(format, "MM") == 1 && strings.Count(format, "M") == 2 {
format = strings.Replace(format, "MM", month, 1)
} else {
panic("format month error! please 'MM'")
}
}

//day
if strings.ContainsAny(format, "d") {

var day string

if t.Day() < 10 {
day = "0" + strconv.Itoa(t.Day())
} else {
day = strconv.Itoa(t.Day())
}

if strings.Count(format, "dd") == 1 && strings.Count(format, "d") == 2 {
format = strings.Replace(format, "dd", day, 1)
} else {
panic("format day error! please 'dd'")
}
}

//hour
if strings.ContainsAny(format, "H") {

var hour string

if t.Hour() < 10 {
hour = "0" + strconv.Itoa(t.Hour())
} else {
hour = strconv.Itoa(t.Hour())
}

if strings.Count(format, "HH") == 1 && strings.Count(format, "H") == 2 {
format = strings.Replace(format, "HH", hour, 1)
} else {
panic("format hour error! please 'HH'")
}
}

//minute
if strings.ContainsAny(format, "m") {

var minute string

if t.Minute() < 10 {
minute = "0" + strconv.Itoa(t.Minute())
} else {
minute = strconv.Itoa(t.Minute())
}
if strings.Count(format, "mm") == 1 && strings.Count(format, "m") == 2 {
format = strings.Replace(format, "mm", minute, 1)
} else {
panic("format minute error! please 'mm'")
}
}

//second
if strings.ContainsAny(format, "s") {

var second string

if t.Second() < 10 {
second = "0" + strconv.Itoa(t.Second())
} else {
second = strconv.Itoa(t.Second())
}

if strings.Count(format, "ss") == 1 && strings.Count(format, "s") == 2 {
format = strings.Replace(format, "ss", second, 1)
} else {
panic("format second error! please 'ss'")
}
}

return format
}



time_test.go


package utils

import "time"
import "testing"
import "fmt"

func TestFormat(t *testing.T) {

fmt.Println(Format(time.Now(), "yyyy/MM/dd"))

fmt.Println(Format(time.Now(), "yyyy-MM-dd HH:mm:ss"))

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值