golang-module / carbon Goto Github PK
View Code? Open in Web Editor NEWA simple, semantic and developer-friendly golang package for time
Home Page: https://pkg.go.dev/github.com/golang-module/carbon/v2
License: MIT License
A simple, semantic and developer-friendly golang package for time
Home Page: https://pkg.go.dev/github.com/golang-module/carbon/v2
License: MIT License
经测试,xorm中如果设置了xorm:"created"或xorm:"updated",那么xorm会把这个字段类型当做time.Time处理,所以会造成reflect.Value.Convert: value of type time.Time cannot be converted to type carbon.ToDateTimeString
的报错,所以建议不要把自更新的字段设为carbon类型或者使用engine.NoAutoTime()禁止自动更新。
carbon.Parse("2019-08-05 13:14:15").DiffForHumans()
是空??
执行go get -u github.com/golang-mod
命令返回下面错误:
第一种
go: github.com/golang-module/carbon upgrade => v1.1.2
go get: github.com/golang-module/[email protected]: parsing go.mod:
module declares its path as: gitee.com/go-package/carbon
but was required as: github.com/golang-module/carbon
第二种
go: downloading github.com/golang-module/carbon v1.2.0
go get github.com/golang-module/carbon: github.com/golang-module/[email protected]: verifying module: checksum mismatch
downloaded: h1:CjyPY0XyUDG32Pb/Z85x+kPWVMb4Q0Yk6wR1Vmtvsrk=
sum.golang.org: h1:b0MjeLmBcnswp+jbXQXDAPwFiuMkpjI5ddEuNBsxMos=
SECURITY ERROR
This download does NOT match the one reported by the checksum server.
The bits may have been replaced on the origin server, or an attacker may
have intercepted the download attempt.
两种情况随机出现。
carbon.Parse("2020-08-05 13:14:15").DiffForHumans(carbon.Now())测试返回空白
自然是需要考虑**的法定的节假日日期不固定,节假日也会从周六日借.
now := sunday()
now.EndOfWeek() will be the next week's end time.
// 将 Carbon 转换成 time.Time
carbon.SetTimezone(carbon.Shanghai).Now().Carbon2Time() 或 carbon.SetTimezone(carbon.Shanghai).Now().Time
设置时区后,转成标准库 time.Time, 没有带时区转换。
模型定义:
type OperationLog struct {
ID int `json:"id" gorm:"primary_key;AUTO_INCREMENT"`
UserId int `json:"user_id" gorm:"-"`
Path string `json:"path" gorm:"-"`
Method string `json:"method" gorm:"-"`
Ip string `json:"ip" gorm:"-"`
Input JSON `json:"input" gorm:"-"`
CreatedAt carbon.ToDateTimeString `json:"created_at"`
UpdatedAt carbon.ToDateTimeString `json:"updated_at"`
}
错误内容:
2020/09/23 21:25:46 http: panic serving 127.0.0.1:62249: json: error calling MarshalJSON for type carbon.ToDateTimeString: invalid character '-' after top-level value
goroutine 91 [running]:
net/http.(*conn).serve.func1(0xc0000d0320)
/usr/local/go/src/net/http/server.go:1801 +0x147
panic(0x49e16c0, 0xc0028352c0)
/usr/local/go/src/runtime/panic.go:975 +0x3e9
go-admin/middleware.CustomError.func1(0xc000ace000)
/Users/zxdstyle/go/go-admin/middleware/customerror.go:44 +0x5d3
panic(0x49e16c0, 0xc0028352c0)
/usr/local/go/src/runtime/panic.go:969 +0x175
github.com/gin-gonic/gin/render.JSON.Render(...)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/render/json.go:59
github.com/gin-gonic/gin.(*Context).Render(0xc000ace000, 0xc8, 0x4c34d80, 0xc0028191c0)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:841 +0x149
github.com/gin-gonic/gin.(*Context).JSON(...)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:884
go-admin/apis/user.Login(0xc000ace000)
/Users/zxdstyle/go/go-admin/apis/user/login.go:21 +0x155
github.com/gin-gonic/gin.(*Context).Next(0xc000ace000)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x3b
go-admin/middleware.RequestId.func1(0xc000ace000)
/Users/zxdstyle/go/go-admin/middleware/requestid.go:24 +0x199
github.com/gin-gonic/gin.(*Context).Next(0xc000ace000)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x3b
go-admin/middleware.Options(0xc000ace000)
/Users/zxdstyle/go/go-admin/middleware/header.go:23 +0x3d
github.com/gin-gonic/gin.(*Context).Next(0xc000ace000)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x3b
go-admin/middleware.NoCache(0xc000ace000)
/Users/zxdstyle/go/go-admin/middleware/header.go:15 +0x16a
github.com/gin-gonic/gin.(*Context).Next(0xc000ace000)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x3b
go-admin/middleware.CustomError(0xc000ace000)
/Users/zxdstyle/go/go-admin/middleware/customerror.go:48 +0x4e
github.com/gin-gonic/gin.(*Context).Next(0xc000ace000)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x3b
go-admin/middleware.LoggerToFile.func1(0xc000ace000)
/Users/zxdstyle/go/go-admin/middleware/logger.go:22 +0x6b
github.com/gin-gonic/gin.(*Context).Next(0xc000ace000)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x3b
github.com/gin-gonic/gin.(*Engine).handleHTTPRequest(0xc00043c3c0, 0xc000ace000)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:409 +0x67a
github.com/gin-gonic/gin.(*Engine).ServeHTTP(0xc00043c3c0, 0x4c3b340, 0xc000aca000, 0xc0000d6100)
/Users/zxdstyle/go/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:367 +0x14d
net/http.serverHandler.ServeHTTP(0xc0005660e0, 0x4c3b340, 0xc000aca000, 0xc0000d6100)
/usr/local/go/src/net/http/server.go:2843 +0xa3
net/http.(*conn).serve(0xc0000d0320, 0x4c3e600, 0xc000abc000)
/usr/local/go/src/net/http/server.go:1925 +0x8ad
created by net/http.(*Server).Serve
/usr/local/go/src/net/http/server.go:2969 +0x36c
^C2020-09-23 21:26:00 Shutdown Server ...
^[[A2020-09-23 21:26:00.922 server.go:116: Server exiting
In somecase, I need convert carbon object to time.Time.
Currently, I need convert carbon to timestamp and then convert to time.Time
For example a database model defined in legacy project as below,
type Post struct {
ID string
CreatedAt null.Time
UpdatedAt null.Time
...
}
post := Post{}
c := carbon.Now()
timestamp := c.ToTimestamp()
post.CreatedAt = null.FromTime(time.Unix(timestamp))
...
If there are many time fields in Post struct, it's boring to do the converting manually on each field.
But it would be clean like this
post.CreatedAt = null.FromTime(carbon.Now().ToTimeDotTime())
It's much appreciate if this awesome project add a method to get time.Time.
代码示例有明显的错误
// 用法一,使用carbon.GormModel自动维护id、created_at、updated_at、deleted_at
type User struct {
carbon.GormModel
Name string `json:"name"`
Age int `json:"age"`
Birthday carbon.ToDateTimeString `json:"birthday"`
}
user := User {
Name: "勾国印"
Age: 18
Birthday: "2012-09-09 00:00:00" // 这里字符串无法赋值给ToDateString类型,结构体赋值也缺少必要逗号
}
// 用法二,不使用carbon.GormModel
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Birthday carbon.ToDateString `json:"birthday"`
CreatedAt carbon.ToDateTimeString `json:"created_at"`
UpdatedAt carbon.ToTimeString `json:"updated_at"`
DeletedAt carbon.ToTimestamp `json:"deleted_at"`
}
user := User {
Name: "勾国印"
Age: 18
Birthday: "2012-09-09 00:00:00" // 这里字符串无法赋值给ToDateString类型,结构体赋值也缺少必要逗号
}
另外在使用gorm
时, carbon.ToDateString
类型的字段无法直接赋值carbon.New().Now()
,两者之间的转换无法无缝衔接
貌似跟直接用time.Time
唯一的区别就是支持了几种不同的时间格式
Format方法返回空字符串 ,系统全崩 。
package main
import (
"fmt"
"github.com/golang-module/carbon"
)
func main() {
s := carbon.Now().Format("Y-m-d H:i:s")
fmt.Println("==============", s)
}
toady := carbon.Now()
f := toady.Format("U.u") // => 1618396403.312
假如想让 毫秒长度 保留到6位该如何写?
代码:
`package main
import (
"fmt"
"github.com/golang-module/carbon"
)
func main() {
fmt.Println(carbon.ParseByFormat("It is 2020-08-05 13:14:15", "It is Y-m-d H:i:s").ToDateString())
fmt.Println(carbon.ParseByLayout("2020|08|05 13|14|15", "2006|01|02 15:04:05").ToDateTimeString())
}`
无任何输出
期望ToTimestamp()可以加入微妙,纳秒输出
carbon := carbon:New()
应该是 carbon := carbon.New()
。IsLastDay
和IsFisrtDay
方法复制IsSunday
方法后忘了修改了calendar.go gives an error: imported and not used "strconv"
建议所有对外输出采用接口的形式,而不是struct函数直接硬撸,这样可以有效解耦并提高可扩展性
应该是gorm,xorm?
Very good package. Time zone seems incomplete
原生库也有这个问题,但是官方不认为这是个bug
c := carbon.New().CreateFromDate(2020, 1, 31).AddMonths(1)
fmt.Println(c.Format("Y-m-d H:i:s"))
输出 2020-03-02 00:00:00
加了一个月,直接变3月了
所以后面我建议你这个库可以把这个修订一下或新增一个额外的添加月份的方法
时间戳没有毫秒的吗?
c := carbon.Now().ToTimestamp()
b := time.Now().UnixNano() / int64(time.Millisecond)
1603956642
1603956642535
parse方法使用的是本地时区,而没有读取carbon示例里设置的时区,carbon.sertimezone().parse("").timestamp()不正确无法根据时区变化
carbon version: 1.3.9 or 1.4.2
dataTime := carbon.Now().ToFormatString("Mon, 02 Jan 2006 15:04:05 GMT")
fmt.Println(dataTime)
output: Julo7, 02 Jpm7 2006 15:04:05 17JulCST
dataTime = time.Now().Format("Mon, 02 Jan 2006 15:04:05 GMT")
fmt.Println(dataTime)
output: Thu, 22 Jul 2021 17:45:54 GMT
parse方法使用的是本地时区,而没有读取carbon示例里设置的时区,carbon.sertimezone().parse("") 得到的不是指定时区的对象,而是local时区的。。。。
I want to parse a time string with timezone Asia/Shanghai
and output with timezone utc how can I do this correctly?
现在一旦解析时间出错,直接panic,这是不是太暴力了,一旦没处理好直接导致程序奔溃,建议增加api让使用者可以判断是否解析出错了,比如
var isError bool = carbon.Parse("2020-11-11 123").IsError()
// 或者像Gorm那样
var err error = carbon.Parse("2020-11-11 123").Error
解析出错直接 panic 真的很不好处理,除了在 defer 去消化就没其他方法了
Hello,
I encountered an issue with the following code:
carbon.Parse("2021-07-24").AddDays(2).WeekOfMonth()
carbon version: 1.4.3
golang version: 1.16
I expected to get:
4
But I actually get:
6
Thanks!
package model
import (
"github.com/golang-module/carbon"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primarykey" json:"id"`
UnionID string `json:"union_id"`
CreatedAt carbon.ToDateTimeString `json:"created_at"`
UpdatedAt carbon.ToDateTimeString `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
Status uint `gorm:"type:tinyint;index" json:"status"`
}
At present, the following languages are supported
Ask for help to translate carbon in other languages, thanks for your contribution.
c.Now().LastOfMonth() // 2020-09-30 00:00:00
月末 按道理应该输出: 2020-09-30 23:59:59 吧?
github.com/golang-module/carbon v1.3.7
carbon.SetLocale(carbon.Shanghai).Parse("2021-04-09").ToTimestampWithMillisecond() 解析不出来
carbon.SetLocale(carbon.Shanghai).ParseByFormat("2021-04-09", “Y-m-d”).ToTimestampWithMillisecond() 解析不出来
carbon.Parse("2021-04-09").ToTimestampWithMillisecond() 正常
carbon.ParseByFormat("2021-04-09", “Y-m-d”).ToTimestampWithMillisecond() 正常
carbon.SetLocale(carbon.Shanghai).ParseByLayout("2021-04-09", "2006-01-02").ToTimestampWithMillisecond() 正常
ts := carbon.Time2Carbon(time.Now())
tStr := ts.Format("2006-01-02 15:04:05")
fmt.Println(tStr)
tStr输出不是当前时间 而是 2006-01-02 15:04:05
定义十天干 甲乙丙丙
包版本:1.3.3
使用示例代码:
c := carbon.Now().AddHours(1).SetLocale("zh-CN")
if c.Error != nil {
// 错误处理
log.Fatal(c.Error)
}
// 狮子座
fmt.Println(c.Constellation())
proto文件里的google.protobuf.Timestamp和gorm,time.Time之间的转换有吗?
实现类似于:几小时前 几分钟前 这样的功能
希望越做越好!
希望添加农历操作
carbon.ParseByFormat("It is 2020-08-05 13:14:15", "It is Y-m-d H:i:s").ToDateTimeString()输出空,错误信息
the value "It is 2020-08-05 13:14:15" can't parse string as carbon
建议增加:
1.是否相等
2.是否不等
3.是否在之后
4.是否在之前
5.是否在两个时间中间
虽然通过现有的比较方法也能实现上述的功能,还是希望大佬能封装一下
$ date --iso-8601=ns
2021-04-23T09:17:28,235575783+08:00 //on Ubuntu 20.4
2021-04-23T09:18:11,357706892+0800 //on CentOS 7.6
This library failed to parse these formats.
中文环境下,
StartOfMonth()
EndOfWeek()
这两个方法,如何将周日作为一周的开始,周六作为一周的结束
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.