date

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2024 License: MIT Imports: 4 Imported by: 5

README

Date Package

Build Status Go Report Card GoDoc Coverage Status

The date package provides a custom date type in Go, designed specifically for use cases where only the date (year, month, day) is needed, without any time or timezone information. This type replaces the standard time.Time type in scenarios where time and timezone components are unnecessary.

Features

  • Nullable date type, comparable and sortable.
  • Stores date as a hex integer (0xYYYYMMDD), making it efficient in memory and database storage.
  • Converts easily between date.Date and time.Time.
  • Marshals and unmarshals to and from JSON.
  • Compatible with SQL database operations.

Installation

To install the package, use:

go get github.com/axkit/date

Usage

Here’s how to use the date package:

Import the Package
import "github.com/axkit/date"
Creating a New Date

You can create a new date using the New function, which accepts the year, month, and day as arguments:

d := date.New(2023, time.January, 1)
fmt.Println(d.String()) // Output: 2023-01-01
Working with Today’s Date

To get today’s date:

today := date.Today()
fmt.Println(today.String()) // Output: current date in YYYY-MM-DD format
Converting to time.Time

To convert date.Date to time.Time:

t := d.Time() // Local time zone
utc := d.UTC() // UTC time zone
Adding Years, Months, and Days

You can add time to a date.Date:

d := date.New(2023, time.January, 1)
newDate := d.Add(1, 0, 0) // Adds 1 year
fmt.Println(newDate.String()) // Output: 2024-01-01
Parsing a Date from String

To parse a date from a string:

var d date.Date
err := d.Parse("2023-01-01")
if err != nil {
    fmt.Println("Error parsing date:", err)
}
fmt.Println(d.String()) // Output: 2023-01-01
Checking Validity

You can check if a date.Date is null or valid:

if d.Valid() {
    fmt.Println("Date is valid")
} else {
    fmt.Println("Date is null")
}
Database Operations

The date.Date type is compatible with SQL databases, implementing both the Scanner and Valuer interfaces.

Storing to Database
stmt, _ := db.Prepare("INSERT INTO dates (date) VALUES (?)")
_, err := stmt.Exec(d)
if err != nil {
    fmt.Println("Error inserting date:", err)
}
Retrieving from Database
var d date.Date
err := db.QueryRow("SELECT date FROM dates WHERE id = ?", id).Scan(&d)
if err != nil {
    fmt.Println("Error scanning date:", err)
}
fmt.Println(d.String())

JSON Marshaling and Unmarshaling

The date.Date type supports JSON encoding and decoding:

type Example struct {
    Date date.Date `json:"date"`
}

e := Example{Date: date.New(2023, time.January, 1)}
jsonData, _ := json.Marshal(e)
fmt.Println(string(jsonData)) // Output: {"date":"2023-01-01"}

Running Tests

To run tests for the date package:

go test github.com/axkit/date

License

This project is licensed under the MIT License - see the LICENSE file for details.


This README provides an overview of the package's features, how to install it, and how to use its primary functions.

Documentation

Overview

Package date provides a custom date type that omits time and timezone components, serving as a replacement for the standard time.Time type where only the date part is needed.

Index

Constants

This section is empty.

Variables

View Source
var (
	Separator         byte = '-'
	DatabaseSeparator byte = '-'

	// FiveYearBefore represents the date five years before today.
	FiveYearBefore = Today().Add(-5, 0, 0)
	// FiveYearAfter represents the date five years from today.
	FiveYearAfter = Today().Add(5, 0, 0)
)

Predefined variables

Functions

func InitPreformattedValues

func InitPreformattedValues(from, to Date)

InitPreformattedValues initializes preformatted date values between a specified range. This function populates two maps, pfm and pjm, for date-to-string and string-to-date conversions, respectively, to optimize date marshaling and unmarshaling.

Types

type Date

type Date uint32

Date represents a nullable date type that excludes time and timezone information. Internally, it stores the year, month, and day as a combined hex integer (0xYYYYMMDD), making it comparable and sortable as an integer. In a database, it is stored as DATE. A null (empty) value is represented in memory as 0.

func New

func New(y int, m time.Month, d int) Date

New creates a Date from the specified year, month, and day.

func Null

func Null() Date

Null returns a null Date (equivalent to zero).

func Parse

func Parse(s string) (Date, error)

Parse converts a string in "YYYY-MM-DD" format into a Date. If the input string is enclosed in quotes, they are removed before parsing.

func Today

func Today() Date

Today returns the current date as a Date instance.

func (Date) Add

func (d Date) Add(years, months, days int) Date

Add returns a new Date that is the result of adding the specified number of years, months, and days to the original Date.

func (Date) Day

func (d Date) Day() int

Day returns the day component of the Date.

func (Date) In added in v0.3.0

func (d Date) In(loc *time.Location) time.Time

In converts a Date to a time.Time instance in the specified location.

func (Date) Month

func (d Date) Month() time.Month

Month returns the month component of the Date.

func (*Date) Parse

func (d *Date) Parse(s string) error

Parse sets the Date from a string in the format "YYYY-MM-DD".

func (*Date) Scan

func (d *Date) Scan(value interface{}) error

Scan sets the Date from a database value.

func (Date) String

func (d Date) String() string

String returns the date as a string formatted as "YYYY-MM-DD". If the date is null, an empty string is returned.

func (Date) Time

func (d Date) Time() time.Time

Time converts a Date to a time.Time instance in the local timezone.

func (Date) UTC

func (d Date) UTC() time.Time

UTC converts a Date to a time.Time instance in UTC.

func (Date) Valid

func (d Date) Valid() bool

Valid returns false if the Date is null.

func (Date) Value

func (d Date) Value() (driver.Value, error)

Value returns the Date as a driver.Value for database storage.

func (Date) Year

func (d Date) Year() int

Year returns the year component of the Date.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL