Go-carbon v2.3.0 was released, a simple, semantic and developer-friendly golang package for datetime

Go-carbon v2.3.0 Christmas special version is released. This should be the last version in 2023. I wish everyone a Merry Christmas!
Carbon is a simple, semantic and developer-friendly golang package for datetime.

Carbon has been included by awesome-go , if you think it is helpful, please give me a star.

github.com/golang-module/carbon

Installation

Go version >= 1.16
go get -u github.com/golang-module/carbon/v2

import  "github.com/golang-module/carbon/v2"
JSON handling
Define model
type Person struct {
  Name string `json:"name"`
  Age int `json:"age"`
  Birthday carbon.Carbon `json:"birthday" carbon:"layout:2006-01-02"`
  GraduatedAt carbon.Carbon `json:"graduated_at" carbon:"layout:15:04:05"`
  CreatedAt carbon.Carbon `json:"created_at" carbon:"layout:2006-01-02 15:04:05"`
}

or

type Person struct {
  Name string `json:"name"`
  Age int `json:"age"`
  Birthday carbon.Carbon `json:"birthday" carbon:"format:Y-m-d"`
  GraduatedAt carbon.Carbon `json:"graduated_at" carbon:"format:H:i:s"`
  CreatedAt carbon.Carbon `json:"created_at" carbon:"format:Y-m-d H:i:s"`
}
Instantiate model
now := Parse("2020-08-05 13:14:15", PRC)
person := Person {
  Name:        "gouguoyin",
  Age:         18,
  Birthday:    now,
  GraduatedAt: now,
  CreatedAt:   now,
}
JSON encode
err1 := carbon.LoadTag(&person)
if err1 != nil {
  // Error handle...
  log.Fatal(err1)
}
data, err2 := json.Marshal(person)
if err2 != nil {
  // Error handle...
  log.Fatal(err2)
}
fmt.Printf("%s", data)
// Output
{
  "name": "gouguoyin",
  "age": 18,
  "birthday": "2020-08-05",
  "graduated_at": "13:14:15",
  "created_at": "2020-08-05 13:14:15"
}
JSON decode
str := `{
  "name": "gouguoyin",
  "age": 18,
  "birthday": "2020-08-05",
  "graduated_at": "13:14:15",
  "created_at": "2020-08-05 13:14:15"
}`
var person Person

err1 := carbon.LoadTag(&person)
if err1 != nil {
  // Error handle...
  log.Fatal(err1)
}

err2 := json.Unmarshal([]byte(str), &person)
if err2 != nil {
  // Error handle...
  log.Fatal(err2)
}

fmt.Sprintf("%s", person.Birthday) // 2002-08-05
fmt.Sprintf("%s", person.GraduatedAt) // 13:14:15
fmt.Sprintf("%s", person.CreatedAt) // 2002-08-05 13:14:15
Change log
  • Fix bug in DiffInYears and Agemethods #181
  • Fix bug with lost time zone after json.Unmarshal #178
  • Move CreateFromStdTime method from carbon.go to creator.go
  • Move ToStdTime method from carbon.go to outputer.go
  • Move deprecated methods as FromStdTime, Time2Carbon and Carbon2Time to deprecated.go
  • Update stretchr/testify to v1.8.4
3 Likes

cool , very helpful ,thanks

1 Like

Welcome to provide valuable feedback

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.