Skip to content

MARS Engine - DateTime Object

The DateTime object in MARS Engine provides a complete API for working with date and time values.
It supports parsing from formatted strings, arithmetic operations, comparisons and timezone adjustments.

Constructors

A DateTime object can be instantiated in two ways:

1. From a format and date string

js
let d1 = new DateTime('uuuu-MM-dd HH:mm:ss', '1993-12-20 12:30:15');
let d2 = new DateTime('uuuu-MM-dd', '1992-12-19');

All supported format symbols follow Java’s DateTimeFormatter standard.

2. From separate date and time parts

js
let d3 = new DateTime(1993, 12, 20, 12, 30, 11);

Order of parameters:

  1. year
  2. month (1–12)
  3. day (1–28/31)
  4. hour (0–23)
  5. minute (0–59)
  6. second (0–59)

Functions

Set Time Zone

js
d1.setZone('+5');

Adjusts the object to the given timezone (e.g., '+1', '-3').

Convert to String

js
let d1String = d1.toString();  // "1993-12-20T12:30:15"

Compare DateTimes

You can compare DateTime objects using after() and before() methods:

js
let d1After = d1.after(d2, d3);   // true
let d1Before = d1.before(d2, d3); // false

Multiple DateTime objects can be passed as arguments.

Arithmetic Operations

Add or subtract date/time components with addYears(), addMonths(), addDays(), addHours(), addMinutes(), and addSeconds().

Use negative values to subtract:

js
d1 = d1.addYears(-1);
d1 = d1.addMonths(-1);
d1 = d1.addDays(2);
d1 = d1.addHours('-1');
d1 = d1.addMinutes('1');
d1 = d1.addSeconds('1');

Each operation returns a new DateTime object.

Epoch (Unix) Timestamp

Get milliseconds since epoch:

js
let unixTime = d1.getEpochMilliseconds();

Properties

You can access individual components directly:

js
write('d1.year', d1.year);             // 1993
write('d1.month', d1.month);           // 12
write('d1.day', d1.day);               // 20
write('d1.hour', d1.hour);             // 17
write('d1.minute', d1.minute);         // 30
write('d1.second', d1.second);         // 15
write('d1.millisecond', d1.millisecond); // 0
write('d1.dayOfYear', d1.dayOfYear);   // 354
write('d1.dayOfWeek', d1.dayOfWeek);   // 1

Full Example

js
let d1 = new DateTime('uuuu-MM-dd HH:mm:ss', '1993-12-20 12:30:15');
let d2 = new DateTime('uuuu-MM-dd', '1992-12-19');
let d3 = new DateTime(1993, 12, 20, 12, 30, 11);

d1.setZone('+5');

let unixTime = d1.getEpochMilliseconds();
write('unixTime', unixTime); // 756390615000

write('d1', d1); // 1993-12-20T17:30:15
write('d2', d2); // 1992-12-19T00:00:00
write('d3', d3); // 1993-12-20T12:30:11

// Comparisons
let d1AfterD2D3 = d1.after(d2, d3);
let d1BeforeD2D3 = d1.before(d2, d3);

// Add/Subtract time parts
d1 = d1.addYears(-1);
d1 = d1.addMonths(-1);
d1 = d1.addDays(2);
d1 = d1.addHours('-1');
d1 = d1.addMinutes('1');
d1 = d1.addSeconds('1');
write('d1_afterAddingTimeParts', d1); // 1992-11-22T11:31:16