go time 工具库

smartwalle · 2018-05-21 12:36:50 · 1118 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2018-05-21 12:36:50 的主题,其中的信息可能已经有所发展或是发生改变。

项目地址

https://github.com/smartwalle/time4go

Time4Go

Go 语言的时间工具库。

帮助

在集成的过程中有遇到问题,欢迎加 QQ 群 564704807 讨论。

安装

$ go get github.com/smartwalle/time4go

开始

package main

import (
    "fmt"
    "github.com/smartwalle/time4go"
    "time"
)

func main() {
    var now = time4go.Now()
    fmt.Println(now)

    var d = time4go.Date(2018, time.May, 20, 13, 14, 0, 0, time.Local)
    fmt.Println(d)
}

获取当前日期所在周的第一天和最后一天

var now = time4go.Now()
now.BeginningDateOfWeek()
now.EndDateOfWeek()

获取当前日期所在月的第一天和最后一天

var now = time4go.Now()
now.BeginningDateOfMonth()
now.EndDateOfMonth()

JSON

  • 设置序列化成 JSON 字符串时的格式
time4go.JSONFormatter = time4go.DefaultFormatter{Layout: "2006-01-02 15:04:05"}
  • 自定义 Formatter

当然你也可以自定义 Formatter,只需要实现以下接口即可:

type TimeFormatter interface {
    Format(t time.Time) ([]byte, error)
    Parse(data []byte) (time.Time, error)
}

比如:

type MyFormatter struct {
}

func (this MyFormatter) Format(t time.Time) ([]byte, error) {
    ...
}

func (this MyFormatter) Parse(data []byte) (time.Time, error) {
    ...
}

time4go.JSONFormatter = MyFormatter{}

支持 SQL 类数据库

db, err := sql.Open("mysql", "xxx")
if err != nil {
    fmt.Println("连接数据库出错:", err)
    return
}
defer db.Close()
db.Exec("INSERT INTO `user` (`name`, `age`, `created_on`) VALUES (?, ?, ?)", "test", 18, time4go.Now())

License

This project is licensed under the MIT License.


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1118 次点击  ∙  2 赞  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传