Introduction to the

Front-line developers use date and time functions, timers, active time processing, and more on a daily basis. The time library is not very flexible to use, especially for date-time creation and computation. Carbon library is a time extension library based on the PHP carbon library. Provide an easy-to-use interface. This article introduces the library.

Quick to use

Third-party libraries need to be installed first:

$ go get github.com/uniplaces/carbon
Copy the code

After using:

package main

import (
  "fmt"
  "time"

  "github.com/uniplaces/carbon"
)

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

  today, _ := carbon.NowInLocation("Japan")
  fmt.Printf("Right now in Japan 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("Happy time!")}}Copy the code

The carbon library is fully compatible with the time. time type of the standard library. In fact, the datetime type of the carbon library is directly embedded in the structure, so the time. time method can be called directly:

// src/github.com/uniplaces/carbon/carbon.go
type Carbon struct {
  time.Time
  weekStartsAt time.Weekday
  weekEndsAt   time.Weekday
  weekendDays  []time.Weekday
  stringFormat string
  Translator   *Translator
}
Copy the code

Second, it simplifies creation. Create a time object. If the time zone is not local or UTC, you need to call LoadLocation to load the corresponding time zone. The time zone object is then passed to the time.date method for creation. Carbon can pass the time zone name directly.

Carbon also provides a number of methods for calculating dates, such as AddDay, SubWeek, etc., which are obvious by name.

The time zone

Before we get into anything else, let’s talk about this time zone problem. Here’s a quote from Wikipedia:

Time zones are regions of the earth that use the same definition of time. In the past, people determined time by looking at the position of the sun (hour Angle), which made it different in places with different longitudes (local time). The concept of time zones was first used in 1863. Time zones partly solve this problem by setting a standard time for a region. Different countries in the world are located in different parts of the earth, so the time of sunrise and sunset is bound to vary from country to country, especially those with a long east-west span. These deviations are known as jet lag.

For example, Tokyo in Japan is located in the east 9th district, Beijing is located in the east 8th district, so Japan is one hour ahead of China, 14:00 in Japan is 13:00 in China.

In Linux, time zones are typically stored in directories like /usr/share/zoneinfo. There are many files in this directory, one for each time zone. The time zone file is a binary file. You can run info tzfile to view the format.

The common format for a time zone name is city, or country/city, or continent/city. Either a city name, a country name +/+ city name, or a continent name +/+ city name. For example, the time zone of Shanghai is Asia/Shanghai, and the time zone of Hong Kong is Asia/Hong_Kong. There are also special ones, such as UTC, Local, etc.

Go language for portability, in the installation package provides the time zone file, in the installation directory (I was C:\Go) lib/time/zoneinfo.zip file, you can perform unzip to see 😀.

To create a time zone, use the Go standard library time.

package main

import (
  "fmt"
  "log"
  "time"
)

func main(a) {
  loc, err := time.LoadLocation("Japan")
  iferr ! =nil {
    log.Fatal("failed to load location: ", err)
  }

  d := time.Date(2020, time.July, 24.20.0.0.0, loc)
  fmt.Printf("The opening ceremony of next olympics will start at %s in Japan\n", d)
}
Copy the code

Using carbon doesn’t have to be so troublesome:

package main

import (
  "fmt"
  "log"
  "time"

  "github.com/uniplaces/carbon"
)

func main(a) {
  c, err := carbon.Create(2020, time.July, 24.20.0.0.0."Japan")
  iferr ! =nil {
    log.Fatal(err)
  }

  fmt.Printf("The opening ceremony of next olympics will start at %s in Japan\n", c)
}
Copy the code

Time operation

A time operation using the time library requires defining a time.Duration object. The time library defines a precision of only nanoseconds to hours:

const (
  Nanosecond  Duration = 1
  Microsecond = 1000 * Nanosecond
  Millisecond = 1000 * Microsecond
  Second      = 1000 * Millisecond
  Minute      = 60 * Second
  Hour        = 60 * Minute
)
Copy the code

Other times need to be constructed using time.ParseDuration, and time.ParseDuration cannot construct other times of precision. If you want to add/subtract the year/month/day, you need to use the AddDate method of time. time:

package main

import (
  "fmt"
  "log"
  "time"
)

func main(a) {
  now := time.Now()

  fmt.Println("now is:", now)

  fmt.Println("one second later is:", now.Add(time.Second))
  fmt.Println("one minute later is:", now.Add(time.Minute))
  fmt.Println("one hour later is:", now.Add(time.Hour))

  d, err := time.ParseDuration("3m20s")
  iferr ! =nil {
    log.Fatal(err)
  }
  fmt.Println("3 minutes and 20 seconds later is:", now.Add(d))

  d, err = time.ParseDuration("2h30m")
  iferr ! =nil {
    log.Fatal(err)
  }
  fmt.Println("2 hours and 30 minutes later is:", now.Add(d))

  fmt.Println("3 days and 2 hours later is:", now.AddDate(0.0.3).Add(time.Hour*2))}Copy the code

Note that all time operations return a new object. The original object is not modified. The same is true of the Carbon library. The Go library also advises against using Pointers to time. time. Of course, carbon library can also use the above method, it also provides a variety of granularity method:

package main

import (
  "fmt"

  "github.com/uniplaces/carbon"
)

func main(a) {
  now := carbon.Now()

  fmt.Println("now is:", now)

  fmt.Println("one second later is:", now.AddSecond())
  fmt.Println("one minute later is:", now.AddMinute())
  fmt.Println("one hour later is:", now.AddHour())
  fmt.Println("3 minutes and 20 seconds later is:", now.AddMinutes(3).AddSeconds(20))
  fmt.Println("2 hours and 30 minutes later is:", now.AddHours(2).AddMinutes(30))
  fmt.Println("3 days and 2 hours later is:", now.AddDays(3).AddHours(2))}Copy the code

Carbon also provides:

  • increasequarterMethod:AddQuarters/AddQuarterThe plural of a multiple is 1.
  • increasecenturyMethod:AddCenturies/AddCentury;
  • increaseWorking daysMethod:AddWeekdays/AddWeekday, this method skips non-working days;
  • increaseweeksMethod:AddWeeks/AddWeek.

In fact, passing a negative number to the above method means a reduction, and carbon also provides the corresponding Sub* method.

A little time

The library time can use the time.Time object’s Before/After/Equal to determine whether it is Before, After, or Equal to another time object. The Carbon library can also compare times using the above method. In addition, it provides groups of methods, each with a short name and a detailed name:

  • Eq/EqualTo: Whether or not it is equal;
  • Ne/NotEqualTo: Whether unequal;
  • Gt/GreaterThan: Whether after;
  • Lt/LessThan: Whether before;
  • Lte/LessThanOrEqual: Whether identical or prior to;
  • Between: Whether it is between two times.

In addition, Carbon provides:

  • The current time is the day of the week.IsMonday/IsTuesday/... /IsSunday;
  • Whether it’s weekdays, weekends, leap years, past time or future time:IsWeekday/IsWeekend/IsLeapYear/IsPast/IsFuture.
package main

import (
  "fmt"

  "github.com/uniplaces/carbon"
)

func main(a) {
  t1, _ := carbon.CreateFromDate(2010.10.1."Asia/Shanghai")
  t2, _ := carbon.CreateFromDate(2011.10.20."Asia/Shanghai")

  fmt.Printf("t1 equal to t2: %t\n", t1.Eq(t2))
  fmt.Printf("t1 not equal to t2: %t\n", t1.Ne(t2))

  fmt.Printf("t1 greater than t2: %t\n", t1.Gt(t2))
  fmt.Printf("t1 less than t2: %t\n", t1.Lt(t2))

  t3, _ := carbon.CreateFromDate(2011.1.20."Asia/Shanghai")
  fmt.Printf("t3 between t1 and t2: %t\n", t3.Between(t1, t2, true))

  now := carbon.Now()
  fmt.Printf("Weekday? %t\n", now.IsWeekday())
  fmt.Printf("Weekend? %t\n", now.IsWeekend())
  fmt.Printf("LeapYear? %t\n", now.IsLeapYear())
  fmt.Printf("Past? %t\n", now.IsPast())
  fmt.Printf("Future? %t\n", now.IsFuture())
}
Copy the code

We can also use carbon to calculate the difference in seconds, minutes, hours, and days between two dates:

package main

import (
  "fmt"

  "github.com/uniplaces/carbon"
)

func main(a) {
  vancouver, _ := carbon.Today("Asia/Shanghai")
  london, _ := carbon.Today("Asia/Hong_Kong")
  fmt.Println(vancouver.DiffInSeconds(london, true)) / / 0

  ottawa, _ := carbon.CreateFromDate(2000.1.1."America/Toronto")
  vancouver, _ = carbon.CreateFromDate(2000.1.1."America/Vancouver")
  fmt.Println(ottawa.DiffInHours(vancouver, true)) / / 3

  fmt.Println(ottawa.DiffInHours(vancouver, false)) / / 3
  fmt.Println(vancouver.DiffInHours(ottawa, false)) // -3

  t, _ := carbon.CreateFromDate(2012.1.31."UTC")
  fmt.Println(t.DiffInDays(t.AddMonth(), true))  / / 31
  fmt.Println(t.DiffInDays(t.SubMonth(), false)) / / - 31

  t, _ = carbon.CreateFromDate(2012.4.30."UTC")
  fmt.Println(t.DiffInDays(t.AddMonth(), true)) / / 30
  fmt.Println(t.DiffInDays(t.AddWeek(), true))  / / 7

  t, _ = carbon.CreateFromTime(10.1.1.0."UTC")
  fmt.Println(t.DiffInMinutes(t.AddSeconds(59), true))  / / 0
  fmt.Println(t.DiffInMinutes(t.AddSeconds(60), true))  / / 1
  fmt.Println(t.DiffInMinutes(t.AddSeconds(119), true)) / / 1
  fmt.Println(t.DiffInMinutes(t.AddSeconds(120), true)) / / 2
}
Copy the code

formatting

We know that time. time provides a Format method. Compared to other programming languages that use formatters to describe formats (memorizing the meaning of %d/%m/%h, etc.), Go provides a simpler and more intuitive way to use Layout. That is, we pass in a date string that says what we want to format. Go replaces the corresponding part of the string with the current time:

package main

import (
  "fmt"
  "time"
)

func main(a) {
  t := time.Now()
  fmt.Println(t.Format("The 2006-01-02 10:00:00"))}Copy the code

All we need to do is pass in 2006-01-02 10:00:00 to indicate that we want the format to be YYYY-MM-DD HH: MM: SS, saving us the trouble of remembering.

For ease of use, Go has some standard time formats built in:

// src/time/format.go
const (
  ANSIC       = "Mon Jan _2 15:04:05 2006"
  UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
  RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
  RFC822      = "02 Jan 06 15:04 MST"
  RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
  RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
  RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
  RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
  RFC3339     = "2006-01-02T15:04:05Z07:00"
  RFC3339Nano = "The 2006-01-02 T15:04:05. 999999999 z07:00"
  Kitchen     = "3:04PM"
  // Handy time stamps.
  Stamp      = "Jan _2 15:04:05"
  StampMilli = "Jan _2 15:04:05. 000." "
  StampMicro = "Jan _2 15:04:05. 000000." "
  StampNano  = "Jan _2 15:04:05. 000000000." "
)
Copy the code

In addition to these formats, Carbon provides several other formats:

// src/github.com/uniplaces/carbon
const (
  DefaultFormat       = "The 2006-01-02 15:04:05"
  DateFormat          = "2006-01-02"
  FormattedDateFormat = "Jan 2, 2006"
  TimeFormat          = "15:04:05"
  HourMinuteFormat    = "15:04"
  HourFormat          = "15"
  DayDateTimeFormat   = "Mon, Aug 2, 2006 3:04 PM"
  CookieFormat        = "Monday, 02-Jan-2006 15:04:05 MST"
  RFC822Format        = "Mon, 02 Jan 06 15:04:05 -0700"
  RFC1036Format       = "Mon, 02 Jan 06 15:04:05 -0700"
  RFC2822Format       = "Mon, 02 Jan 2006 15:04:05 -0700"
  RSSFormat           = "Mon, 02 Jan 2006 15:04:05 -0700"
)
Copy the code

Note that the time library defaults to 2006-01-02 15:04:05.9999999-0700 MST, which is a bit more complicated. The carbon library defaults to 2006-01-02 15:04:05.

Advanced features

decorator

A modifier is used to obtain the start and end times for specific times. For example, the start and end time of the day, month, quarter, year, decade, century, week, and the time of the previous Tuesday, the next Monday, the next working day, etc. :

package main

import (
  "fmt"
  "time"

  "github.com/uniplaces/carbon"
)

func main(a) {
  t := carbon.Now()
  fmt.Printf("Start of day:%s\n", t.StartOfDay())
  fmt.Printf("End of day:%s\n", t.EndOfDay())
  fmt.Printf("Start of month:%s\n", t.StartOfMonth())
  fmt.Printf("End of month:%s\n", t.EndOfMonth())
  fmt.Printf("Start of year:%s\n", t.StartOfYear())
  fmt.Printf("End of year:%s\n", t.EndOfYear())
  fmt.Printf("Start of decade:%s\n", t.StartOfDecade())
  fmt.Printf("End of decade:%s\n", t.EndOfDecade())
  fmt.Printf("Start of century:%s\n", t.StartOfCentury())
  fmt.Printf("End of century:%s\n", t.EndOfCentury())
  fmt.Printf("Start of week:%s\n", t.StartOfWeek())
  fmt.Printf("End of week:%s\n", t.EndOfWeek())
  fmt.Printf("Next:%s\n", t.Next(time.Wednesday))
  fmt.Printf("Previous:%s\n", t.Previous(time.Wednesday))
}
Copy the code

Customize weekdays and weekends

In some areas the start of the week, the end of the week is different than ours. For example, Sunday is the start of a new week in the United States. That’s okay, Carbon can customize the start and end of the week:

package main

import (
  "fmt"
  "log"
  "time"

  "github.com/uniplaces/carbon"
)

func main(a) {
  t, err := carbon.Create(2020.02.11.0.0.0.0."Asia/Shanghai")
  iferr ! =nil {
    log.Fatal(err)
  }

  t.SetWeekStartsAt(time.Sunday)
  t.SetWeekEndsAt(time.Saturday)
  t.SetWeekendDays([]time.Weekday{time.Monday, time.Tuesday, time.Wednesday})

  fmt.Printf("Today is %s, weekend? %t\n", t.Weekday(), t.IsWeekend())
}
Copy the code

conclusion

Carbon provides a lot of utility methods, and the time method can also be used, making it very powerful. Time is a complex issue that, given time zones, leap seconds, daylight saving time everywhere, can be a crematorium to deal with on your own. Thanks to these libraries (┬ _ ┬)

reference

  1. Carbon GitHub Repository: github.com/uniplaces/c…

I

My blog

Welcome to follow my wechat public account [GoUpUp], learn together, progress together ~

This article is published by OpenWrite!