Skip to content

DateTime

The DateTime class in Lua provides an object-oriented interface to handle date and time data, enabling a large range of time manipulation operations. This class is ideal for any usecase requiring date manipulation and comparison features, such as scheduling systems, time-tracking software, or any scenario where precise control over dates and times is necessary.

Usage

To use this class, add the following require at the top of your script:

local DateTime = require 'engine/datetime'

Reference

__new

__new(year, month, day, hour, minute, second)

Creates a new DateTime object

Parameters

  • year (number): The year
  • month (number): The month (1-12)
  • day (number): The day of the month (1-31)
  • hour (number): The hour (0-23)
  • minute (number): The minute (0-59)
  • second (number): The second (0-59)

toString

toString()

Returns the datetime as a string

Returns

  • string: datetime in YYYY-MM-DD HH:MM:SS format

isLeapYear

isLeapYear()

Checks if the year is a leap year

Returns

  • boolean: if leap year, false otherwise

getDaysInMonth

getDaysInMonth()

Gets the number of days in the month

Returns

  • number: of days in the month

addSeconds

addSeconds(seconds)

Adds seconds to the current datetime

Parameters

  • seconds (number): Number of seconds to add

addMinutes

addMinutes(minutes)

Adds minutes to the current datetime

Parameters

  • minutes (number): Number of minutes to add

addHours

addHours(hours)

Adds hours to the current datetime

Parameters

  • hours (number): Number of hours to add

addDays

addDays(days)

Adds days to the current datetime

Parameters

  • days (number): Number of days to add

addMonths

addMonths(months)

Adds months to the current datetime (handles overflow)

Parameters

  • months (number): Number of months to add

addYears

addYears(years)

Adds years to the current datetime

Parameters

  • years (number): Number of years to add

compare

compare(other)

Compares two DateTime objects

Parameters

  • other (DateTime): The other datetime to compare

Returns

  • number: if this datetime is earlier, 0 if equal, 1 if later

equals

equals(other)

Checks if two datetimes are equal

Parameters

  • other (DateTime): The other datetime to compare

Returns

  • boolean: if equal, false otherwise

now

static now()

Creates a DateTime object representing the current date and time

Returns

  • DateTime: current date and time

toTimestamp

toTimestamp()

Converts the DateTime object to a Unix timestamp

Returns

  • number: Unix timestamp

fromTimestamp

static fromTimestamp(timestamp)

Creates a DateTime object from a Unix timestamp

Parameters

  • timestamp (number): The Unix timestamp

Returns

  • DateTime: corresponding DateTime object