Carbon for Golang, an extension for Time

Related tags

Date and Time carbon
Overview

Carbon

Build Status Go Report Card codecov GoDoc License

A simple extension for Time based on PHP's Carbon library.

Features:

  • Time is embedded into Carbon (provides access to all of Time's functionality)
  • Supports addition and subtraction of dates
  • Provides methods to compare dates
  • Supports date formatting in common formats
  • Easily calculate difference between dates
  • Ease testing with dates by using carbon.Freeze() and carbon.Now()

To do:

  • Implement all localization features as in Carbon
  • Improve the code style to be more idiomatic Go

Getting started

Install Carbon:

go get github.com/uniplaces/carbon

Add to your imports to start using Carbon

import "github.com/uniplaces/carbon"

Examples

A simple example to get you started:

package main

import (
	"fmt"
	"time"

	"github.com/uniplaces/carbon"
)

func main() {
	fmt.Printf("Right now is %s\n", carbon.Now().DateTimeString())

	today, _ := carbon.NowInLocation("America/Vancouver")
	fmt.Printf("Right now in Vancouver is %s\n", today)

	fmt.Printf("Tomorrow is %s\n", carbon.Now().AddDay())
	fmt.Printf("Last week is %s\n", carbon.Now().SubWeek())

	nextOlympics, _ := carbon.CreateFromDate(2016, time.August, 5, "Europe/London")
	nextOlympics = nextOlympics.AddYears(4)
	fmt.Printf("Next olympics are in %d\n", nextOlympics.Year())

	if carbon.Now().IsWeekend() {
		fmt.Printf("Party time!")
	}
}

You can also check the examples/ folder for more examples.

Contributing

Please feel free to make suggestions, create issues, fork the repository and send pull requests!

Licence

Copyright 2016 UNIPLACES

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Issues
  • Add fallback when loading lang file

    Add fallback when loading lang file

    Description

    The lang files in the lang folder existed in the package, but when retrieved, it will search for the lang folder in the working directory (which is good, especially if you wanted to do some customization for the translations).
    This pull-request is intended to add a fallback logic for retrieving the lang file.

    Motivation and Context

    This is a possible action item for https://github.com/uniplaces/carbon/issues/58 and https://github.com/uniplaces/carbon/issues/54. Although, you could just copy the lang folder or any lang file you desire to solve the issue.

    How Has This Been Tested?

    I've added a unit-test to cover the case, but can only cater for negative test-case. Instead, I've tested at my local by pushing the changes into my forked repo, then testing with another go file with syntax:

    prevTime := time.Now().AddDate(0, 0, -3)
    registeredAt := carbon.NewCarbon(prevTime)
    currentTime := carbon.NewCarbon(time.Now())
    
    difference, err := registeredAt.DiffForHumans(currentTime, false, false, false)
    if err != nil {
    log.Println(err.Error())
    }
    
    log.Println(difference)
    

    Approach

    If the working directory does not have the lang file, it will check the downloaded/installed directory of the package from GoPath, then using the lang file from there.

    opened by necrophidia 4
  • Index out of range when using DiffForHumans function

    Index out of range when using DiffForHumans function

    Hey, I was going to use this wonderful function of yours called DIffForHumans but it turns out that It was crashing the application because of an index out of range error. The error says that it occurred while invoking the method chooseUnit for the translator which crashes when calling line 81:

    return strings.Replace(s[1], ":count", strconv.FormatInt(int64(count), 10), 1), nil
    

    I looked at the current translator that was associated with the carbon obtained through carbon.NewCarbon(time.Time) and the t.resources map was empty which could have been the cause of the index out of range error.

    I'm not sure if this is helpful for you guys but here's basically how I invoked the method:

    registeredAt := carbon.NewCarbon(comment.CreatedAt)
    currentTime := carbon.NewCarbon(time.Now())
    
    difference, err := registeredAt.DiffForHumans(currentTime,true,false,false)
    if err != nil {
     fmt.Println(err.Error())
    }
    
    return difference
    

    My apologies if I misunderstood the way this method works or how I should use it, I'm still a little bit unexperienced.

    opened by amartine59 4
  • The timestamp will change after calling the `carbon.CreateFromTimestampUTC()` method

    The timestamp will change after calling the `carbon.CreateFromTimestampUTC()` method

    unix := time.Now().UTC().Unix()
    utcTime, _ := carbon.CreateFromTimestampUTC(unix)
    if unix != utcTime.Unix() {
        fmt.Println(unix, utcTime.Unix())
    }
    

    Why are unix and utcTime.Unix() not equal? I got 1543837131 1543865931

    bug 
    opened by BigKuCha 4
  • Add Carbon Period functionality

    Add Carbon Period functionality

    Adds a simple Carbon Period functionality https://carbon.nesbot.com/docs/#api-period that only accepts

    1. Start date
    2. period in days
    3. End date

    It returns an array of Carbon.

    opened by gmhafiz 3
  • Incorrect daydatetime format string

    Incorrect daydatetime format string

    func TestTimestampFormat(t *testing.T)  {
    	c, err := carbon.CreateFromTimestamp(1624647416, "UTC")
    	assert.Nil(t, err)
    	assert.Equal(t, "Fri, Jun 25, 2021 6:56 PM", c.DayDateTimeString())
    }
    

    The above timestamp is from june 25 6:56pm utc image

    Error:      	Not equal: 
            	            	expected: "Fri, Jun 25, 2021 6:56 PM"
            	            	actual  : "Fri, Aug 25, 2021 6:56 PM"
            	            	
            	            	Diff:
            	            	--- Expected
            	            	+++ Actual
            	            	@@ -1 +1 @@
            	            	-Fri, Jun 25, 2021 6:56 PM
            	            	+Fri, Aug 25, 2021 6:56 PM
            	Test:       	TestTimestampFormat
    

    Issue is due to wrong format string used in

    	DayDateTimeFormat   = "Mon, Aug 2, 2006 3:04 PM"
    
    
    opened by sahutd 3
  • DiffInYears producing incorrect output

    DiffInYears producing incorrect output

    Hi, I've noticed DiffInYears seems to produce incorrect output, unless I'm mistaken.

    Test case:

    package main
    
    import (
        "testing"
        "time"
    
        "github.com/stretchr/testify/assert"
        "github.com/uniplaces/carbon"
    )
    
    func TestCarbonDiffInYears(t *testing.T) {
        dob, _ := carbon.CreateFromDate(2000, time.June, 27, time.UTC.String())
    
        yesterday, _ := carbon.CreateFromDate(2016, time.June, 26, time.UTC.String())
        today, _ := carbon.CreateFromDate(2016, time.June, 27, time.UTC.String())
        tomorrow, _ := carbon.CreateFromDate(2016, time.June, 28, time.UTC.String())
    
        // Day before 16th birthday... Should be 15
        assert.Equal(t, int64(15), dob.DiffInYears(yesterday, true))
        // Day of 16th birthday
        assert.Equal(t, int64(16), dob.DiffInYears(today, true))
        // Day after 16th birthday
        assert.Equal(t, int64(16), dob.DiffInYears(tomorrow, true))
    }
    

    Result:

    $ go test -v
    === RUN   TestCarbonDiffInYears
    --- FAIL: TestCarbonDiffInYears (0.00s)
            Error Trace:    carbon_test.go:19
        Error:      Not equal:
                expected: 15
                received: 16
    
    FAIL
    exit status 1
    FAIL    github.com/bbrks/carbon-test    0.011s
    
    bug 
    opened by bbrks 3
  • BUG: EndOfWeek may go to the next week when it is sunday!

    BUG: EndOfWeek may go to the next week when it is sunday!

    opened by iflamed 2
  • [RFC] Change internal Time instead of creating new Carbon instance

    [RFC] Change internal Time instead of creating new Carbon instance

    Current version is creating a new carbon instance every time it needs to use Go's Time library for calculations. This PR makes it so the internal Time is changed in those instances.

    opened by mumia 2
  • vendor/ folder

    vendor/ folder

    (accidentally hit enter before I meant to, my bad)

    It's generally not good practice to vendor dependencies inside a library, Go itself doesn't really support nested vendor/ folders, and so anyone then vendoring carbon will either flatten, or remove the nested folder here :)

    opened by fortytw2 2
  • [RFC] Fix language, use go:embed

    [RFC] Fix language, use go:embed

    Use go:embed https://pkg.go.dev/embed to not need to declare GOPATH and have language support.

    This way we can have access to the languages. However, It requires that we use go version above 1.16.

    opened by rntdrts 1
  • added null checks to NewCarbonInterval

    added null checks to NewCarbonInterval

    package main
    
    import "github.com/uniplaces/carbon"
    
    func main() {
    	carbon.NewCarbonInterval(nil, nil)
    }
    

    This simple code would panic because there are no null checks in NewCarbonInterval.

    https://github.com/uniplaces/carbon/blob/1c77b657f1c27f275c6a835cf0ddb77764fa6577/carboninterval.go#L16

    According to Go Code Review Comments

    Error strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context.

    opened by ashwek 2
Releases(v0.2.2)
  • v0.2.2(Apr 28, 2022)

    What's Changed

    • Add Carbon Period functionality by @gmhafiz in https://github.com/uniplaces/carbon/pull/78

    New Contributors

    • @gmhafiz made their first contribution in https://github.com/uniplaces/carbon/pull/78

    Full Changelog: https://github.com/uniplaces/carbon/compare/v0.2.1...v0.2.2

    Source code(tar.gz)
    Source code(zip)
  • v0.2.1(Apr 17, 2022)

    What's Changed

    • [RFC] Fix month calculation between dates by @rntdrts in https://github.com/uniplaces/carbon/pull/77

    Full Changelog: https://github.com/uniplaces/carbon/compare/v0.2.0...v0.2.1

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Apr 16, 2022)

    What's Changed

    • goenv >= 1.16
    • [RFC] Fix language, use go:embed by @rntdrts in https://github.com/uniplaces/carbon/pull/76

    Full Changelog: https://github.com/uniplaces/carbon/compare/v0.1.7...v0.2.0

    Source code(tar.gz)
    Source code(zip)
  • v0.1.7(Apr 16, 2022)

    What's Changed

    • [RFC][NI] Migrate CI to Github actions by @rntdrts in https://github.com/uniplaces/carbon/pull/64
    • [RFC]Fix end of the week when the date provider is the end of the week by @rntdrts in https://github.com/uniplaces/carbon/pull/66
    • [RFC]Migrate to go modules by @rntdrts in https://github.com/uniplaces/carbon/pull/65
    • Add fallback when loading lang file by @necrophidia in https://github.com/uniplaces/carbon/pull/67
    • fixing daydatetimeformat string layout by @Rossalli in https://github.com/uniplaces/carbon/pull/71
    • [RFC] Fix tests names so they are executed by @rntdrts in https://github.com/uniplaces/carbon/pull/75
    • [RFC] Fix incorrect diff in months by @rntdrts in https://github.com/uniplaces/carbon/pull/74

    New Contributors

    • @rntdrts made their first contribution in https://github.com/uniplaces/carbon/pull/64
    • @necrophidia made their first contribution in https://github.com/uniplaces/carbon/pull/67
    • @Rossalli made their first contribution in https://github.com/uniplaces/carbon/pull/71

    Full Changelog: https://github.com/uniplaces/carbon/compare/v0.1.6...v0.1.7

    Source code(tar.gz)
    Source code(zip)
  • v0.1.6(Jan 16, 2019)

  • v0.1.3(Nov 14, 2018)

  • v0.1.2(Jun 25, 2018)

  • v0.1.1(Jun 20, 2018)

Owner
Uniplaces LTD
Code it, live it
Uniplaces LTD
:clock1: Date and Time - Golang Formatting Library

Kair Date and Time - Golang Formatting Library Setup To get Kair > Go CLI go get github.com/GuilhermeCaruso/kair > Go DEP dep ensure -add github.com/G

Guilherme Caruso 23 Mar 15, 2022
Now is a time toolkit for golang

Now Now is a time toolkit for golang Install go get -u github.com/jinzhu/now Usage Calculating time based on current time import "github.com/jinzhu/n

Jinzhu 3.8k Aug 18, 2022
Golang package to manipulate time intervals.

timespan timespan is a Go library for interacting with intervals of time, defined as a start time and a duration. Documentation API Installation Insta

null 82 Jun 19, 2022
timeutil - useful extensions (Timedelta, Strftime, ...) to the golang's time package

timeutil - useful extensions to the golang's time package timeutil provides useful extensions (Timedelta, Strftime, ...) to the golang's time package.

Kyoung-chan Lee 189 Jul 5, 2022
time format golang

a simple plugin to change date and time format

Ibnu Surkati 2 Sep 29, 2021
Go-timeparser - Flexible Time Parser for Golang

go-timeparser Flexible Time Parser for Golang Installation Download timeparser w

Kazuaki Yamamoto 1 Jun 9, 2022
:clock8: Better time duration formatting in Go!

durafmt durafmt is a tiny Go library that formats time.Duration strings (and types) into a human readable format. go get github.com/hako/durafmt Why

Wesley Hill 442 Aug 6, 2022
Go time library inspired by Moment.js

Goment Current Version: 1.4.0 Changelog Goment is a port of the popular Javascript datetime library Moment.js. It follows the Moment.js API closely, w

Nick Leeper 191 Jul 30, 2022
fasttime - fast time formatting for go

fasttime - fast time formatting for go

phuslu 38 Jul 25, 2022
🌐 A time zone helper

?? A time zone helper tz helps you schedule things across time zones. It is an interactive TUI program that displays time across a few time zones of y

Arnaud Berthomier 679 Aug 8, 2022
Clock is a small library for mocking time in Go.

clock Clock is a small library for mocking time in Go. It provides an interface around the standard library's time package so that the application can

Ben Johnson 566 Aug 5, 2022
A natural language date/time parser with pluggable rules

when when is a natural language date/time parser with pluggable rules and merge strategies Examples tonight at 11:10 pm at Friday afternoon the deadli

Oleg Lebedev 1.2k Aug 15, 2022
Copy of stdlib's time.Duration, but ParseDuration accepts other bigger units such as days, weeks, months and years

duration Copy of stdlib's time.Duration, but ParseDuration accepts other units as well: d: days (7 * 24 * time.Hour) w: weeks (7 * Day) mo: months (30

Carlos Alexandro Becker 11 Jun 21, 2022
Structural time package for jalali calendar

Jalali Structural time package for jalali calendar. This package support parse from string, json and time. Structures There are three data structures

Bardo Go Framework 1 Mar 21, 2022
Show time by timezone

Show time by timezone

Michael Bruskov 1 Jan 22, 2022
Timediff is a Go package for printing human readable, relative time differences 🕰️

timediff is a Go package for printing human readable, relative time differences. Output is based on ranges defined in the Day.js JavaScript library, and can be customized if needed.

MergeStat 283 Aug 15, 2022
GoLang Parse many date strings without knowing format in advance.

Go Date Parser Parse many date strings without knowing format in advance. Uses a scanner to read bytes and use a state machine to find format. Much fa

Aaron Raddon 1.8k Aug 10, 2022
Convert string to duration in golang

Go String To Duration (go-str2duration) This package allows to get a time.Duration from a string. The string can be a string retorned for time.Duratio

Santiago De la Cruz 42 Jul 26, 2022
A simple, semantic and developer-friendly golang package for datetime

Carbon 中文 | English carbon 是一个轻量级、语义化、对开发者友好的 Golang 时间处理库,支持链式调用和 gorm、xorm、zorm 等主流 orm。 如果您觉得不错,请给个 star 吧 github:github.com/golang-module/carbon g

null 2.2k Aug 17, 2022