temporal

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2025 License: MIT Imports: 8 Imported by: 0

README

Value Object Temporal

Overview

The Value Object Temporal component provides immutable value objects for representing and manipulating temporal concepts such as dates, times, durations, and intervals in the ServiceLib library.

Features

  • Immutable Values: All temporal value objects are immutable
  • Type Safety: Strong typing for temporal concepts
  • Validation: Built-in validation for temporal values
  • Comparison Operations: Methods for comparing temporal values
  • Formatting: Methods for formatting temporal values

Installation

go get github.com/abitofhelp/servicelib/valueobject/temporal

Quick Start

See the Quick Start example for a complete, runnable example of how to use the temporal value objects.

API Documentation

Core Types

Description of the main types provided by the component.

DateVO

Represents a date value object.

type DateVO struct {
    // Fields
}
TimeVO

Represents a time value object.

type TimeVO struct {
    // Fields
}
DateTimeVO

Represents a date-time value object.

type DateTimeVO struct {
    // Fields
}
DurationVO

Represents a duration value object.

type DurationVO struct {
    // Fields
}
IntervalVO

Represents a time interval value object.

type IntervalVO struct {
    // Fields
}
Key Methods

Description of the key methods provided by the component.

NewDateVO

Creates a new date value object.

func NewDateVO(year int, month time.Month, day int) (*DateVO, error)
NewTimeVO

Creates a new time value object.

func NewTimeVO(hour, minute, second, nanosecond int) (*TimeVO, error)
NewDateTimeVO

Creates a new date-time value object.

func NewDateTimeVO(date *DateVO, time *TimeVO) (*DateTimeVO, error)
NewDurationVO

Creates a new duration value object.

func NewDurationVO(duration time.Duration) (*DurationVO, error)
NewIntervalVO

Creates a new interval value object.

func NewIntervalVO(start, end *DateTimeVO) (*IntervalVO, error)

Examples

For complete, runnable examples, see the following directories in the EXAMPLES directory:

  • Basic Usage - Shows basic usage of temporal value objects
  • Comparison - Shows how to compare temporal value objects
  • Formatting - Shows how to format temporal value objects

Best Practices

  1. Immutability: Never modify temporal value objects, always create new ones
  2. Validation: Always validate input when creating temporal value objects
  3. Comparison: Use the provided comparison methods instead of comparing fields directly
  4. Time Zones: Be aware of time zone implications when working with date-time value objects
  5. Formatting: Use the provided formatting methods for consistent output

Troubleshooting

Common Issues
Invalid Date/Time Values

If you encounter validation errors when creating temporal value objects, ensure that the input values are valid (e.g., month between 1-12, day appropriate for the month, etc.).

Time Zone Issues

If you're experiencing unexpected behavior with date-time value objects, check the time zone settings. Consider using UTC for consistency.

Contributing

Contributions to this component are welcome! Please see the Contributing Guide for more information.

License

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

Documentation

Overview

Package temporal provides immutable value objects for representing and manipulating temporal concepts such as dates, times, durations, and versions.

This package implements various temporal value objects that follow the Value Object pattern from Domain-Driven Design (DDD). All temporal value objects are immutable, providing type safety, built-in validation, and comparison operations.

Key features:

  • Immutable values: All temporal value objects are immutable
  • Type safety: Strong typing for temporal concepts
  • Validation: Built-in validation for temporal values
  • Comparison operations: Methods for comparing temporal values
  • Formatting: Methods for formatting temporal values

The package provides several types of temporal value objects:

  • Duration: Represents a duration of time Example: duration, err := temporal.NewDuration(5 * time.Minute)

  • Time: Represents a specific point in time Example: timeVO, err := temporal.NewTime(time.Now())

  • Version: Represents a semantic version (major.minor.patch) Example: version, err := temporal.NewVersion(1, 2, 3)

Best practices when working with temporal value objects:

  1. Never modify temporal value objects; always create new ones
  2. Always validate input when creating temporal value objects
  3. Use the provided comparison methods instead of comparing fields directly
  4. Be aware of time zone implications when working with time value objects
  5. Use the provided formatting methods for consistent output

Example usage:

// Create a duration value object
duration, err := temporal.NewDuration(30 * time.Second)
if err != nil {
    // Handle validation error
}

// Create a time value object
timeVO, err := temporal.NewTime(time.Now())
if err != nil {
    // Handle validation error
}

// Create a version value object
version, err := temporal.NewVersion(2, 1, 0)
if err != nil {
    // Handle validation error
}

// Compare versions
otherVersion, _ := temporal.NewVersion(2, 0, 0)
if version.IsGreaterThan(otherVersion) {
    fmt.Println("Version is newer")
}

All temporal value objects implement the base.ValueObject interface and provide additional methods specific to their temporal nature.

Package temporal provides value objects related to time and duration. It includes implementations for time-based value objects that follow the domain-driven design principles.

Package temporal provides value objects related to time and versioning information.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Duration

type Duration struct {
	base.BaseStructValueObject
	// contains filtered or unexported fields
}

Duration represents a time duration value object. It encapsulates a time.Duration value and provides methods for validation, comparison, formatting, and common duration operations. Duration is immutable; all operations return new Duration instances.

func NewDuration

func NewDuration(duration time.Duration) (Duration, error)

NewDuration creates a new Duration value object with the specified time.Duration value. It validates that the duration is not negative.

Parameters:

  • duration: The time.Duration value to encapsulate.

Returns:

  • A valid Duration value object.
  • An error if the duration is negative.

func ParseDuration

func ParseDuration(s string) (Duration, error)

ParseDuration creates a new Duration value object from a string representation. The string should be in the format accepted by time.ParseDuration, such as "1h30m45s". Empty strings and invalid formats will result in an error.

Parameters:

  • s: The string representation of the duration to parse.

Returns:

  • A valid Duration value object.
  • An error if the string is empty, has an invalid format, or represents a negative duration.

func (Duration) Add

func (v Duration) Add(other Duration) (Duration, error)

Add adds another Duration to this Duration and returns a new Duration. Since Duration is immutable, this method does not modify the original Duration.

Parameters:

  • other: The Duration to add to this Duration.

Returns:

  • A new Duration representing the sum of this Duration and the other Duration.
  • An error if the resulting Duration is invalid.

func (Duration) Equals

func (v Duration) Equals(other Duration) bool

Equals checks if two Duration value objects are equal. Two durations are considered equal if they represent the same amount of time. This method implements the base.Equatable interface.

Parameters:

  • other: The Duration to compare with.

Returns:

  • true if the durations are equal, false otherwise.

func (Duration) Format

func (v Duration) Format(format string) string

Format returns a formatted string representation of the duration. This method provides different formatting options for displaying the duration.

Format options:

  • "short": Returns a format like "1h 30m 45s"
  • "long": Returns a format like "1 hour 30 minutes 45 seconds" with proper pluralization
  • "compact": Returns a format like "1:30:45" (hours:minutes:seconds)
  • Any other value: Returns the default format from String()

Parameters:

  • format: The format to use for the string representation.

Returns:

  • A formatted string representation of the duration.

func (Duration) Hours

func (v Duration) Hours() float64

Hours returns the duration as a floating point number of hours. This method returns the hours with 4 decimal places of precision.

Returns:

  • The duration in hours as a float64, rounded to 4 decimal places.

func (Duration) IsEmpty

func (v Duration) IsEmpty() bool

IsEmpty checks if the Duration is empty (zero value). A Duration is considered empty if it represents zero time. This method implements the base.ValueObject interface.

Returns:

  • true if the duration is zero, false otherwise.

func (Duration) MarshalJSON

func (v Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. It serializes the Duration to JSON by converting it to a map and then to JSON.

Returns:

  • The JSON representation of the Duration as a byte array.
  • An error if JSON marshaling fails.

func (Duration) Milliseconds

func (v Duration) Milliseconds() int64

Milliseconds returns the duration as an integer number of milliseconds. This method is equivalent to time.Duration.Milliseconds().

Returns:

  • The duration in milliseconds as an int64.

func (Duration) Minutes

func (v Duration) Minutes() float64

Minutes returns the duration as a floating point number of minutes. This method returns the minutes with 2 decimal places of precision.

Returns:

  • The duration in minutes as a float64, rounded to 2 decimal places.

func (Duration) Seconds

func (v Duration) Seconds() float64

Seconds returns the duration as a floating point number of seconds. This method is equivalent to time.Duration.Seconds().

Returns:

  • The duration in seconds as a float64.

func (Duration) String

func (v Duration) String() string

String returns the string representation of the Duration. This method implements the fmt.Stringer interface. The format is the same as time.Duration.String(), e.g., "1h30m45s".

Returns:

  • A string representation of the duration.

func (Duration) Subtract

func (v Duration) Subtract(other Duration) (Duration, error)

Subtract subtracts another Duration from this Duration and returns a new Duration. If the result would be negative, it returns a zero duration instead of a negative one. Since Duration is immutable, this method does not modify the original Duration.

Parameters:

  • other: The Duration to subtract from this Duration.

Returns:

  • A new Duration representing the difference between this Duration and the other Duration, or a zero Duration if the result would be negative.
  • An error if the resulting Duration is invalid.

func (Duration) ToMap

func (v Duration) ToMap() map[string]interface{}

ToMap converts the Duration to a map representation. This is useful for serialization and for creating JSON representations.

Returns:

  • A map containing the duration value with the key "duration".

func (Duration) Validate

func (v Duration) Validate() error

Validate checks if the Duration is valid. A Duration is considered valid if it is not negative. This method implements the base.Validatable interface.

Returns:

  • nil if the duration is valid.
  • An error if the duration is negative.

func (Duration) Value

func (v Duration) Value() time.Duration

Value returns the underlying time.Duration value. This method provides access to the encapsulated time.Duration value, allowing interoperability with standard library functions that expect time.Duration.

Returns:

  • The underlying time.Duration value.

type Time

type Time struct {
	base.BaseStructValueObject
	// contains filtered or unexported fields
}

Time represents a time value object based on RFC 3339 format. It encapsulates a time.Time value and provides methods for comparison, arithmetic, and conversion operations.

func NewTime

func NewTime(value time.Time) (Time, error)

NewTime creates a new Time with validation. It returns an error if the validation fails.

func NewTimeFromString

func NewTimeFromString(value string) (Time, error)

NewTimeFromString creates a new Time from an RFC 3339 formatted string. It returns an error if the string is empty or not in valid RFC 3339 format.

func (Time) Add

func (t Time) Add(d time.Duration) Time

Add returns a new Time with the given duration added. It properly handles any errors from the NewTime constructor.

func (Time) After

func (t Time) After(other Time) bool

After checks if this time is after another time.

func (Time) Before

func (t Time) Before(other Time) bool

Before checks if this time is before another time.

func (Time) Equal

func (t Time) Equal(other Time) bool

Equal is maintained for backward compatibility. New code should use Equals() instead.

func (Time) Equals

func (t Time) Equals(other Time) bool

Equals checks if two times are equal. This method follows the naming convention used in other value objects.

func (Time) IsEmpty

func (t Time) IsEmpty() bool

IsEmpty checks if the time is empty (zero value).

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface. It marshals the time as an RFC 3339 formatted string.

func (Time) String

func (t Time) String() string

String returns the RFC 3339 string representation of the time.

func (Time) Sub

func (t Time) Sub(other Time) time.Duration

Sub returns the duration between two times.

func (Time) ToMap

func (t Time) ToMap() map[string]interface{}

ToMap converts the time to a map representation.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface. It unmarshals an RFC 3339 formatted string into a Time.

func (Time) Validate

func (t Time) Validate() error

Validate checks if the Time is valid. Currently, all time.Time values are considered valid. This method is included for consistency with other value objects.

func (Time) Value

func (t Time) Value() time.Time

Value returns the underlying time.Time value.

type Version

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

Version represents a semantic version (major.minor.patch)

func NewVersion

func NewVersion(major, minor, patch int, preRelease, build string) (Version, error)

NewVersion creates a new Version with validation

func ParseVersion

func ParseVersion(s string) (Version, error)

ParseVersion creates a new Version from a string in format "major.minor.patch[-prerelease][+build]"

func (Version) Build

func (v Version) Build() string

Build returns the build metadata

func (Version) CompareTo

func (v Version) CompareTo(other Version) int

CompareTo compares this version to another version Returns:

-1 if this version is less than the other
 0 if this version is equal to the other
 1 if this version is greater than the other

func (Version) Equals

func (v Version) Equals(other Version) bool

Equals checks if two Versions are equal

func (Version) IsEmpty

func (v Version) IsEmpty() bool

IsEmpty checks if the Version is empty (zero value)

func (Version) IsPreRelease

func (v Version) IsPreRelease() bool

IsPreRelease checks if this is a pre-release version

func (Version) Major

func (v Version) Major() int

Major returns the major version number

func (Version) Minor

func (v Version) Minor() int

Minor returns the minor version number

func (Version) NextMajor

func (v Version) NextMajor() Version

NextMajor returns the next major version

func (Version) NextMinor

func (v Version) NextMinor() Version

NextMinor returns the next minor version

func (Version) NextPatch

func (v Version) NextPatch() Version

NextPatch returns the next patch version

func (Version) Patch

func (v Version) Patch() int

Patch returns the patch version number

func (Version) PreRelease

func (v Version) PreRelease() string

PreRelease returns the pre-release identifier

func (Version) String

func (v Version) String() string

String returns the string representation of the Version

func (Version) ToMap

func (v Version) ToMap() map[string]interface{}

ToMap converts the Version to a map[string]interface{}

func (Version) Validate

func (v Version) Validate() error

Validate checks if the Version is valid

Jump to

Keyboard shortcuts

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