datetime

package
v3.0.0-...-40211c2 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: BSD-2-Clause Imports: 8 Imported by: 0

Documentation

Overview

Package with support of Tarantool's datetime data type.

Datetime data type supported in Tarantool since 2.10.

Since: 1.7.0

See also:

* Datetime Internals https://github.com/tarantool/tarantool/wiki/Datetime-Internals

Example

Example demonstrates how to use tuples with datetime. To enable support of datetime import tarantool/datetime package.

dialer := tarantool.NetDialer{
	Address:  "127.0.0.1:3013",
	User:     "test",
	Password: "test",
}
opts := tarantool.Opts{}
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
conn, err := tarantool.Connect(ctx, dialer, opts)
if err != nil {
	fmt.Printf("Error in connect is %v", err)
	return
}

var datetime = "2013-10-28T17:51:56.000000009Z"
tm, err := time.Parse(time.RFC3339, datetime)
if err != nil {
	fmt.Printf("Error in time.Parse() is %v", err)
	return
}
dt, err := MakeDatetime(tm)
if err != nil {
	fmt.Printf("Unable to create Datetime from %s: %s", tm, err)
	return
}

space := "testDatetime_1"
index := "primary"

// Replace a tuple with datetime.
data, err := conn.Do(tarantool.NewReplaceRequest(space).
	Tuple([]interface{}{dt}),
).Get()
if err != nil {
	fmt.Printf("Error in replace is %v", err)
	return
}
respDt := data[0].([]interface{})[0].(Datetime)
fmt.Println("Datetime tuple replace")
fmt.Printf("Data: %v\n", respDt.ToTime())

// Select a tuple with datetime.
var offset uint32 = 0
var limit uint32 = 1
data, err = conn.Do(tarantool.NewSelectRequest(space).
	Index(index).
	Offset(offset).
	Limit(limit).
	Iterator(tarantool.IterEq).
	Key([]interface{}{dt}),
).Get()
if err != nil {
	fmt.Printf("Error in select is %v", err)
	return
}
respDt = data[0].([]interface{})[0].(Datetime)
fmt.Println("Datetime tuple select")
fmt.Printf("Data: %v\n", respDt.ToTime())

// Delete a tuple with datetime.
data, err = conn.Do(tarantool.NewDeleteRequest(space).
	Index(index).
	Key([]interface{}{dt}),
).Get()
if err != nil {
	fmt.Printf("Error in delete is %v", err)
	return
}
respDt = data[0].([]interface{})[0].(Datetime)
fmt.Println("Datetime tuple delete")
fmt.Printf("Data: %v\n", respDt.ToTime())

Index

Examples

Constants

View Source
const (
	// NoTimezone allows to create a datetime without UTC timezone for
	// Tarantool. The problem is that Golang by default creates a time value
	// with UTC timezone. So it is a way to create a datetime without timezone.
	NoTimezone = ""
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Adjust

type Adjust int

An Adjust is used as a parameter for date adjustions, see: https://github.com/tarantool/tarantool/wiki/Datetime-Internals#date-adjustions-and-leap-years

const (
	NoneAdjust   Adjust = 0 // adjust = "none" in Tarantool
	ExcessAdjust Adjust = 1 // adjust = "excess" in Tarantool
	LastAdjust   Adjust = 2 // adjust = "last" in Tarantool
)

type Datetime

type Datetime struct {
	// contains filtered or unexported fields
}

func MakeDatetime

func MakeDatetime(t time.Time) (Datetime, error)

MakeDatetime returns a datetime.Datetime object that contains a specified time.Time. It may return an error if the Time value is out of supported range: [-5879610-06-22T00:00Z .. 5879611-07-11T00:00Z] or an invalid timezone or offset value is out of supported range: [-12 * 60 * 60, 14 * 60 * 60].

NOTE: Tarantool's datetime.tz value is picked from t.Location().String(). "Local" location is unsupported, see ExampleMakeDatetime_localUnsupported.

Example (LocalUnsupported)

ExampleMakeDatetime_localUnsupported demonstrates that "Local" location is unsupported.

tm := time.Now().Local()
loc := tm.Location()
fmt.Println("Location:", loc)
if _, err := MakeDatetime(tm); err != nil {
	fmt.Printf("Could not create a Datetime with %s location.\n", loc)
} else {
	fmt.Printf("A Datetime with %s location created.\n", loc)
}
Output:

Location: Local
Could not create a Datetime with Local location.
Example (NoTimezone)

Example demonstrates how to create a datetime for Tarantool without UTC timezone in datetime.

var datetime = "2013-10-28T17:51:56.000000009Z"
tm, err := time.Parse(time.RFC3339, datetime)
if err != nil {
	fmt.Printf("Error in time.Parse() is %v", err)
	return
}

tm = tm.In(time.FixedZone(NoTimezone, 0))

dt, err := MakeDatetime(tm)
if err != nil {
	fmt.Printf("Unable to create Datetime from %s: %s", tm, err)
	return
}

fmt.Printf("Time value: %v\n", dt.ToTime())

func (Datetime) Add

func (d Datetime) Add(ival Interval) (Datetime, error)

Add creates a new Datetime as addition of the Datetime and Interval. It may return an error if a new Datetime is out of supported range.

Example

ExampleDatetime_Add demonstrates how to add an Interval to a Datetime value.

var datetime = "2013-01-31T17:51:56.000000009Z"
tm, err := time.Parse(time.RFC3339, datetime)
if err != nil {
	fmt.Printf("Error in time.Parse() is %s", err)
	return
}
dt, err := MakeDatetime(tm)
if err != nil {
	fmt.Printf("Unable to create Datetime from %s: %s", tm, err)
	return
}

newdt, err := dt.Add(Interval{
	Year:   1,
	Month:  1,
	Sec:    333,
	Adjust: LastAdjust,
})
if err != nil {
	fmt.Printf("Unable to add to Datetime: %s", err)
	return
}

fmt.Printf("New time: %s\n", newdt.ToTime().String())
Output:

New time: 2014-02-28 17:57:29.000000009 +0000 UTC
Example (Dst)

ExampleDatetime_Add_dst demonstrates how to add an Interval to a Datetime value with a DST location.

loc, err := time.LoadLocation("Europe/Moscow")
if err != nil {
	fmt.Printf("Unable to load location: %s", err)
	return
}
tm := time.Date(2008, 1, 1, 1, 1, 1, 1, loc)
dt, err := MakeDatetime(tm)
if err != nil {
	fmt.Printf("Unable to create Datetime: %s", err)
	return
}

fmt.Printf("Datetime time:\n")
fmt.Printf("%s\n", dt.ToTime())
fmt.Printf("Datetime time + 6 month:\n")
fmt.Printf("%s\n", dt.ToTime().AddDate(0, 6, 0))
dt, err = dt.Add(Interval{Month: 6})
if err != nil {
	fmt.Printf("Unable to add 6 month: %s", err)
	return
}
fmt.Printf("Datetime + 6 month time:\n")
fmt.Printf("%s\n", dt.ToTime())
Output:

Datetime time:
2008-01-01 01:01:01.000000001 +0300 MSK
Datetime time + 6 month:
2008-07-01 01:01:01.000000001 +0400 MSD
Datetime + 6 month time:
2008-07-01 01:01:01.000000001 +0400 MSD

func (Datetime) Interval

func (d Datetime) Interval(next Datetime) Interval

Interval returns an Interval value to a next Datetime value.

Example

ExampleDatetime_Interval demonstrates how to get an Interval value between two Datetime values.

var first = "2013-01-31T17:51:56.000000009Z"
var second = "2015-03-20T17:50:56.000000009Z"

tmFirst, err := time.Parse(time.RFC3339, first)
if err != nil {
	fmt.Printf("Error in time.Parse() is %v", err)
	return
}
tmSecond, err := time.Parse(time.RFC3339, second)
if err != nil {
	fmt.Printf("Error in time.Parse() is %v", err)
	return
}

dtFirst, err := MakeDatetime(tmFirst)
if err != nil {
	fmt.Printf("Unable to create Datetime from %s: %s", tmFirst, err)
	return
}
dtSecond, err := MakeDatetime(tmSecond)
if err != nil {
	fmt.Printf("Unable to create Datetime from %s: %s", tmSecond, err)
	return
}

ival := dtFirst.Interval(dtSecond)
fmt.Printf("%v", ival)
Output:

{2 2 0 -11 0 -1 0 0 0}

func (Datetime) MarshalMsgpack

func (d Datetime) MarshalMsgpack() ([]byte, error)

MarshalMsgpack implements a custom msgpack marshaler.

func (Datetime) String

func (d Datetime) String() string

This method converts Datetime to String - formats to ISO8601.

func (Datetime) Sub

func (d Datetime) Sub(ival Interval) (Datetime, error)

Sub creates a new Datetime as subtraction of the Datetime and Interval. It may return an error if a new Datetime is out of supported range.

Example

ExampleDatetime_Sub demonstrates how to subtract an Interval from a Datetime value.

var datetime = "2013-01-31T17:51:56.000000009Z"
tm, err := time.Parse(time.RFC3339, datetime)
if err != nil {
	fmt.Printf("Error in time.Parse() is %s", err)
	return
}
dt, err := MakeDatetime(tm)
if err != nil {
	fmt.Printf("Unable to create Datetime from %s: %s", tm, err)
	return
}

newdt, err := dt.Sub(Interval{
	Year:   1,
	Month:  1,
	Sec:    333,
	Adjust: LastAdjust,
})
if err != nil {
	fmt.Printf("Unable to sub from Datetime: %s", err)
	return
}

fmt.Printf("New time: %s\n", newdt.ToTime().String())
Output:

New time: 2011-12-31 17:46:23.000000009 +0000 UTC

func (*Datetime) ToTime

func (d *Datetime) ToTime() time.Time

ToTime returns a time.Time that Datetime contains.

If a Datetime created from time.Time value then an original location is used for the time value.

If a Datetime created via unmarshaling Tarantool's datetime then we try to create a location with time.LoadLocation() first. In case of failure, we use a location created with time.FixedZone().

func (*Datetime) UnmarshalMsgpack

func (d *Datetime) UnmarshalMsgpack(data []byte) error

UnmarshalMsgpack implements a custom msgpack unmarshaler.

type Interval

type Interval struct {
	Year   int64
	Month  int64
	Week   int64
	Day    int64
	Hour   int64
	Min    int64
	Sec    int64
	Nsec   int64
	Adjust Adjust
}

Interval type is GoLang implementation of Tarantool intervals.

func (Interval) Add

func (ival Interval) Add(add Interval) Interval

Add creates a new Interval as addition of intervals.

Example

ExampleInterval_Add demonstrates how to add two intervals.

orig := Interval{
	Year:   1,
	Month:  2,
	Week:   3,
	Sec:    10,
	Adjust: ExcessAdjust,
}
ival := orig.Add(Interval{
	Year:   10,
	Min:    30,
	Adjust: LastAdjust,
})

fmt.Printf("%v", ival)
Output:

{11 2 3 0 0 30 10 0 1}

func (Interval) MarshalMsgpack

func (ival Interval) MarshalMsgpack() ([]byte, error)

MarshalMsgpack implements a custom msgpack marshaler.

func (Interval) MarshalMsgpackTo

func (ival Interval) MarshalMsgpackTo(e *msgpack.Encoder) error

MarshalMsgpackTo implements a custom msgpack marshaler.

func (Interval) Sub

func (ival Interval) Sub(sub Interval) Interval

Sub creates a new Interval as subtraction of intervals.

Example

ExampleInterval_Sub demonstrates how to subtract two intervals.

orig := Interval{
	Year:   1,
	Month:  2,
	Week:   3,
	Sec:    10,
	Adjust: ExcessAdjust,
}
ival := orig.Sub(Interval{
	Year:   10,
	Min:    30,
	Adjust: LastAdjust,
})

fmt.Printf("%v", ival)
Output:

{-9 2 3 0 0 -30 10 0 1}

func (*Interval) UnmarshalMsgpack

func (ival *Interval) UnmarshalMsgpack(data []byte) error

UnmarshalMsgpack implements a custom msgpack unmarshaler.

func (*Interval) UnmarshalMsgpackFrom

func (ival *Interval) UnmarshalMsgpackFrom(d *msgpack.Decoder) error

UnmarshalMsgpackFrom implements a custom msgpack unmarshaler.

type OptionalDatetime

type OptionalDatetime struct {
	// contains filtered or unexported fields
}

OptionalDatetime represents an optional value of type Datetime. It can either hold a valid Datetime (IsSome == true) or be empty (IsZero == true).

func NoneOptionalDatetime

func NoneOptionalDatetime() OptionalDatetime

NoneOptionalDatetime creates an empty optional OptionalDatetime value. The returned OptionalDatetime will have IsSome() == false and IsZero() == true.

Example:

o := NoneOptionalDatetime()
if o.IsZero() {
    fmt.Println("value is absent")
}

func SomeOptionalDatetime

func SomeOptionalDatetime(value Datetime) OptionalDatetime

SomeOptionalDatetime creates an optional OptionalDatetime with the given Datetime value. The returned OptionalDatetime will have IsSome() == true and IsZero() == false.

func (*OptionalDatetime) DecodeMsgpack

func (o *OptionalDatetime) DecodeMsgpack(decoder *msgpack.Decoder) error

DecodeMsgpack decodes a OptionalDatetime value from MessagePack format. Supports two input types:

  • nil: interpreted as no value (NoneOptionalDatetime)
  • Datetime: interpreted as a present value (SomeOptionalDatetime)

Returns an error if the input type is unsupported or decoding fails.

After successful decoding:

  • on nil: exists = false, value = default zero value
  • on Datetime: exists = true, value = decoded value

func (OptionalDatetime) EncodeMsgpack

func (o OptionalDatetime) EncodeMsgpack(encoder *msgpack.Encoder) error

EncodeMsgpack encodes the OptionalDatetime value using MessagePack format. - If the value is present, it is encoded as Datetime. - If the value is absent (None), it is encoded as nil.

Returns an error if encoding fails.

func (OptionalDatetime) Get

func (o OptionalDatetime) Get() (Datetime, bool)

Get returns the stored value and a boolean flag indicating its presence. If the value is present, returns (value, true). If the value is absent, returns (zero value of Datetime, false).

Recommended usage:

	if value, ok := o.Get(); ok {
     // use value
	}

func (OptionalDatetime) IsNil

func (o OptionalDatetime) IsNil() bool

IsNil is an alias for IsZero.

This method is provided for compatibility with the msgpack Encoder interface.

func (OptionalDatetime) IsSome

func (o OptionalDatetime) IsSome() bool

IsSome returns true if the OptionalDatetime contains a value. This indicates the value is explicitly set (not None).

func (OptionalDatetime) IsZero

func (o OptionalDatetime) IsZero() bool

IsZero returns true if the OptionalDatetime does not contain a value. Equivalent to !IsSome(). Useful for consistency with types where zero value (e.g. 0, false, zero struct) is valid and needs to be distinguished.

func (OptionalDatetime) MustGet

func (o OptionalDatetime) MustGet() Datetime

MustGet returns the stored value if it is present. Panics if the value is absent (i.e., IsZero() == true).

Use with caution — only when you are certain the value exists.

Panics with: "optional value is not set" if no value is set.

func (OptionalDatetime) Unwrap

func (o OptionalDatetime) Unwrap() Datetime

Unwrap returns the stored value regardless of presence. If no value is set, returns the zero value for Datetime.

Warning: Does not check presence. Use IsSome() before calling if you need to distinguish between absent value and explicit zero value.

func (OptionalDatetime) UnwrapOr

func (o OptionalDatetime) UnwrapOr(defaultValue Datetime) Datetime

UnwrapOr returns the stored value if present. Otherwise, returns the provided default value.

Example:

o := NoneOptionalDatetime()
v := o.UnwrapOr(someDefaultOptionalDatetime)

func (OptionalDatetime) UnwrapOrElse

func (o OptionalDatetime) UnwrapOrElse(defaultValue func() Datetime) Datetime

UnwrapOrElse returns the stored value if present. Otherwise, calls the provided function and returns its result. Useful when the default value requires computation or side effects.

Example:

o := NoneOptionalDatetime()
v := o.UnwrapOrElse(func() Datetime { return computeDefault() })

type OptionalInterval

type OptionalInterval struct {
	// contains filtered or unexported fields
}

OptionalInterval represents an optional value of type Interval. It can either hold a valid Interval (IsSome == true) or be empty (IsZero == true).

func NoneOptionalInterval

func NoneOptionalInterval() OptionalInterval

NoneOptionalInterval creates an empty optional OptionalInterval value. The returned OptionalInterval will have IsSome() == false and IsZero() == true.

Example:

o := NoneOptionalInterval()
if o.IsZero() {
    fmt.Println("value is absent")
}

func SomeOptionalInterval

func SomeOptionalInterval(value Interval) OptionalInterval

SomeOptionalInterval creates an optional OptionalInterval with the given Interval value. The returned OptionalInterval will have IsSome() == true and IsZero() == false.

func (*OptionalInterval) DecodeMsgpack

func (o *OptionalInterval) DecodeMsgpack(decoder *msgpack.Decoder) error

DecodeMsgpack decodes a OptionalInterval value from MessagePack format. Supports two input types:

  • nil: interpreted as no value (NoneOptionalInterval)
  • Interval: interpreted as a present value (SomeOptionalInterval)

Returns an error if the input type is unsupported or decoding fails.

After successful decoding:

  • on nil: exists = false, value = default zero value
  • on Interval: exists = true, value = decoded value

func (OptionalInterval) EncodeMsgpack

func (o OptionalInterval) EncodeMsgpack(encoder *msgpack.Encoder) error

EncodeMsgpack encodes the OptionalInterval value using MessagePack format. - If the value is present, it is encoded as Interval. - If the value is absent (None), it is encoded as nil.

Returns an error if encoding fails.

func (OptionalInterval) Get

func (o OptionalInterval) Get() (Interval, bool)

Get returns the stored value and a boolean flag indicating its presence. If the value is present, returns (value, true). If the value is absent, returns (zero value of Interval, false).

Recommended usage:

	if value, ok := o.Get(); ok {
     // use value
	}

func (OptionalInterval) IsNil

func (o OptionalInterval) IsNil() bool

IsNil is an alias for IsZero.

This method is provided for compatibility with the msgpack Encoder interface.

func (OptionalInterval) IsSome

func (o OptionalInterval) IsSome() bool

IsSome returns true if the OptionalInterval contains a value. This indicates the value is explicitly set (not None).

func (OptionalInterval) IsZero

func (o OptionalInterval) IsZero() bool

IsZero returns true if the OptionalInterval does not contain a value. Equivalent to !IsSome(). Useful for consistency with types where zero value (e.g. 0, false, zero struct) is valid and needs to be distinguished.

func (OptionalInterval) MustGet

func (o OptionalInterval) MustGet() Interval

MustGet returns the stored value if it is present. Panics if the value is absent (i.e., IsZero() == true).

Use with caution — only when you are certain the value exists.

Panics with: "optional value is not set" if no value is set.

func (OptionalInterval) Unwrap

func (o OptionalInterval) Unwrap() Interval

Unwrap returns the stored value regardless of presence. If no value is set, returns the zero value for Interval.

Warning: Does not check presence. Use IsSome() before calling if you need to distinguish between absent value and explicit zero value.

func (OptionalInterval) UnwrapOr

func (o OptionalInterval) UnwrapOr(defaultValue Interval) Interval

UnwrapOr returns the stored value if present. Otherwise, returns the provided default value.

Example:

o := NoneOptionalInterval()
v := o.UnwrapOr(someDefaultOptionalInterval)

func (OptionalInterval) UnwrapOrElse

func (o OptionalInterval) UnwrapOrElse(defaultValue func() Interval) Interval

UnwrapOrElse returns the stored value if present. Otherwise, calls the provided function and returns its result. Useful when the default value requires computation or side effects.

Example:

o := NoneOptionalInterval()
v := o.UnwrapOrElse(func() Interval { return computeDefault() })

Jump to

Keyboard shortcuts

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