Referință rapidă

Ghid Rapid Moment.js

Un ghid complet de referinta pentru Moment.js: parsarea datelor, tokenuri de formatare, manipulare, formate localizate si alternative moderne.

· Publicat

Moment.js este o biblioteca JavaScript consacrata pentru parsarea, validarea, modificarea si formatarea datelor calendaristice.

Parsarea și Crearea Datelor

// Timestamp curent
const now = moment();

// Parsare cu sir explicit de formatare
const m = moment('2026-10-25', 'YYYY-MM-DD');

// Parsare timestamp Unix (secunde vs milisecunde)
moment.unix(1730000000); // din secunde
moment(1730000000000);   // din milisecunde

// Verificare validitate
m.isValid(); // -> true

Tokenuri de Formatare

m.format();                  // "2026-10-25T00:00:00+08:00" (// Format standard ISO 8601)
m.format('dddd');            // "Sunday"
m.format('MMM Do YY');       // "Oct 25th 26"
m.fromNow();                 // "// Timp relativ (ex: acum 3 ore)"
m.calendar();                // "// Format calendaristic"

Tabel Tokenuri de Dată

Token Interval de Ieșire Descriere
YYYY 2026 4-digit year
YY 26 2-digit year
MM 01..12 2-digit month
MMM Jan..Dec Short month name
MMMM January..December Full month name
DD 01..31 2-digit day of month
Do 1st..31st Day of month with ordinal
d 0..6 Day of week (0 is Sunday)
ddd Sun..Sat Short day of week
dddd Sunday..Saturday Full day of week
Q 1..4 Quarter of the year

Tabel Tokenuri de Oră

Token Interval de Ieșire Descriere
HH 00..23 24-hour hour (2-digit)
H 0..23 24-hour hour (1-digit)
hh 01..12 12-hour hour (2-digit)
mm 00..59 Minute (2-digit)
ss 00..59 Second (2-digit)
SSS 000..999 Milliseconds (3-digit)
A AM / PM Uppercase meridiem
a am / pm Lowercase meridiem
Z +08:00 Difference from UTC

Manipularea Datelor

Obiectele Moment sunt mutabile. Operatiunile modifica instanta direct:

// Adaugare si scadere
moment().add(7, 'days');
moment().subtract(1, 'month');

// Setare la limita unitatii de timp
moment().startOf('day');  // 00:00:00.000 astazi
moment().endOf('month');  // 23:59:59.999 ultima zi din luna

// Clonare pentru a evita modificarea nedorita
const original = moment();
const nextWeek = original.clone().add(7, 'days');

Formate Predefinite Localizate

Format Exemplu de Ieșire
LT 8:30 PM
LTS 8:30:25 PM
L 10/25/2026
LL October 25, 2026
LLL October 25, 2026 8:30 PM
LLLL Sunday, October 25, 2026 8:30 PM

Alternative Moderne

Moment.js este in modul de mentenanta. Alternative moderne recomandate:

  • date-fns: Functii modulare si imutabile cu suport pentru tree-shaking.
  • Day.js: Biblioteca usoara de 2KB cu API compatibil cu Moment.
  • Luxon: Biblioteca moderna dezvoltata de autorii Moment pe baza Intl.
  • Native Intl.DateTimeFormat: API nativ inclus in navigatoare si Node.js fara dependinte.

Referințe

Subiecte conexe