1: Getting Started with Carbon

1.1 Introduction

A simple, semantic and developer-friendly golang package for datetime

Benefits of using Carbon for datetime handling:

  • Developer-Friendly: Carbon offers a fluent and expressive interface for dealing with datetime that is intuitive for developers.
  • Internationalization Support: Supports internationalization, allowing you to localize your date representations.
  • Immutability: Carbon instances are immutable, meaning they can be safely passed around without unexpected modifications.
  • Timezone Handling: Carbon simplifies the complexity of managing datetimes across different time zones.
  • Extensive API: Provides a comprehensive set of functions for creating, parsing, and formatting dates and times.

1.2 Installation Guide

Installation for Go version >= 1.16

To install the Carbon package for Go version 1.16 or above, use the following command:

go get -u github.com/golang-module/carbon/v2

Then, import the package into your Go file:

import "github.com/golang-module/carbon/v2"

Installation for Go version < 1.16

For older versions of Go, you can still install Carbon using:

go get -u github.com/golang-module/carbon

And import it likewise:

import "github.com/golang-module/carbon"

Note that v1 is no longer actively updated, but it will be maintained for bug fixes.

1.3 Setting Up Your First Carbon Project

Basic configuration of Carbon: Once Carbon is installed, you can start using it by simply creating a new Carbon instance. You can customize Carbon by setting the default global layout, timezone, and locale to suit your project's needs.

Setting the global default layout, timezone, and locale:

carbon.SetDefault(carbon.Default{
  Layout: carbon.RFC3339Layout,
  Timezone: carbon.PRC,
  Locale: "en",
})

If not set explicitly, Carbon has default settings for these — Layout: "2006-01-02 15:04:05", Timezone: Local, Locale: "en".

2: Basic Carbon Operations

2.1 Working with Current Time

Fetching the Current Date and Time

Retrieving the current date and time is a fundamental operation in many applications. With Carbon, you can acquire the current datetime instance by calling the carbon.Now() method. Let's look at how to fetch the current datetime:

// Fetches the current date and time as a Carbon instance.
now := carbon.Now()

fmt.Println("Current datetime:", now)

Displaying Today, Yesterday, and Tomorrow

Carbon provides an elegant way of working with dates relative to the current day. To get the datetime representation of today, yesterday, and tomorrow, you can use the carbon.Now(), carbon.Yesterday(), and carbon.Tomorrow() methods respectively:

// Today's datetime
today := carbon.Now()
fmt.Println("Today:", today.ToDateTimeString())

// Yesterday's datetime
yesterday := carbon.Yesterday()
fmt.Println("Yesterday:", yesterday.ToDateTimeString())

// Tomorrow's datetime
tomorrow := carbon.Tomorrow()
fmt.Println("Tomorrow:", tomorrow.ToDateTimeString())

The methods provide a concise way to interact with these commonly used date references without manual calculations.

Formatting and Representation of Current Time

Carbon facilitates different ways to format and display the datetime. Whether you need a standard format such as ISO8601, a custom format, or a localized version, Carbon has methods to suit these requirements.

Here is how you can format the current datetime in various ways:

// Standard datetime representation
fmt.Println("RFC3339:", now.ToRFC3339String())
fmt.Println("ISO8601:", now.ToIso8601String())

// Custom datetime format
fmt.Println("Custom:", now.Format("Monday, 02-Jan-06 15:04:05 MST"))

// Using predefined layouts
fmt.Println("ANSIC format:", now.ToAnsicString())
fmt.Println("UnixDate format:", now.ToUnixDateString())
fmt.Println("RubyDate format:", now.ToRubyDateString())
fmt.Println("Kitchen format:", now.ToKitchenString())

// For custom patterns, use the Format method
fmt.Println("Custom pattern:", now.Format("2006-01-02 3:04 PM"))

2.2 Carbon Instances Creation

Creating instances from timestamps

In Go, dealing with timestamps is frequent, and Carbon provides intuitive methods to handle them. A timestamp is a sequence of characters or encoded information identifying when a certain event occurred, usually giving date and time of day, sometimes accurate to a small fraction of a second.

To create a Carbon instance from a Unix timestamp, which represents the number of seconds that have elapsed since the Unix epoch (midnight on January 1, 197, UTC), you can use various precision levels:

// Create a Carbon instance from a given timestamp with second precision
c1 := carbon.CreateFromTimestamp(1596604455)
fmt.Println(c1.ToString()) // Outputs: "202-08-05 13:14:15 +080 CST"

// For higher precision (milliseconds), use `CreateFromTimestampMilli`
c2 := carbon.CreateFromTimestampMilli(1596604455999)
fmt.Println(c2.ToString()) // Outputs: "202-08-05 13:14:15.999 +080 CST"

// For microseconds, use `CreateFromTimestampMicro`
c3 := carbon.CreateFromTimestampMicro(1596604455999999)
fmt.Println(c3.ToString()) // Outputs: "202-08-05 13:14:15.999999 +080 CST"

// And for nanoseconds, use `CreateFromTimestampNano`
c4 := carbon.CreateFromTimestampNano(1596604455999999999)
fmt.Println(c4.ToString()) // Outputs: "202-08-05 13:14:15.999999999 +080 CST"

Creating instances from date and time components

If you have the individual components of a date, such as year, month, and day or the components of a time like hour, minute, and second, Carbon can handle these too.

// Create a Carbon instance from a given date only
date := carbon.CreateFromDate(2022, 12, 25)
fmt.Println(date.ToDateString()) // Outputs: "2022-12-25"

// Create a Carbon instance from a given time only
time := carbon.CreateFromTime(23, 59, 59)
fmt.Println(time.ToTimeString()) // Outputs: "23:59:59"

// Create a Carbon instance from both date and time
dateTime := carbon.CreateFromDateTime(2022, 12, 25, 23, 59, 59)
fmt.Println(dateTime.ToDateTimeString()) // Outputs: "2022-12-25 23:59:59"

2.3 Parsing Time Strings

Handling date-time representations as strings is a common scenario. Carbon makes it convenient to parse strings into Carbon instances.

Using carbon.Parse for standard time formats:

// Parse a string with date and time
c := carbon.Parse("202-08-05 13:14:15", carbon.PRC)
if c.Error != nil {
    fmt.Printf("Error: %v", c.Error)
} else {
    fmt.Println(c.ToDateTimeString()) // Outputs: "202-08-05 13:14:15"
}

// Parsing an RFC3339 formatted string
rfc3339 := carbon.Parse("202-08-05T13:14:15+08:00")
fmt.Println(rfc3339.ToString()) // Outputs: "202-08-05 13:14:15 +080 CST"

Custom formats with ParseByFormat and ParseByLayout

You can also parse strings that are in a specific format not directly handled by carbon.Parse.

// Parse a time string as a Carbon instance by format
byFormat := carbon.ParseByFormat("202|08|05 13|14|15", "2006|01|02 15|04|05")
fmt.Println(byFormat.ToDateTimeString()) // Outputs: "202-08-05 13:14:15"

// Parse a time string as a Carbon instance by layout
byLayout := carbon.ParseByLayout("202|08|05", "2006|01|02")
fmt.Println(byLayout.ToDateString()) // Outputs: "202-08-05"

Handling errors

Always check the Error field to ensure parsing was successful:

invalidDate := carbon.Parse("This is not a date", carbon.PRC)
if invalidDate.IsInvalid() {
    fmt.Println("Error parsing date:", invalidDate.Error)
}

Remember, robust error checking is a critical part of working with dates and times to prevent unexpected results or system crashes.