Moment.js es una clasica libreria de JavaScript para parsear, validar, manipular y dar formato a fechas.
Análisis y Creación de Fechas
// Analizar marca de tiempo actual
const now = moment();
// Analizar con formato explicito
const m = moment('2026-10-25', 'YYYY-MM-DD');
// Analizar timestamp Unix (segundos frente a milisegundos)
moment.unix(1730000000); // desde segundos
moment(1730000000000); // desde milisegundos
// Comprobar validez
m.isValid(); // -> true
Tokens de Formateo
m.format(); // "2026-10-25T00:00:00+08:00" (// Formato estandar ISO 8601)
m.format('dddd'); // "Sunday"
m.format('MMM Do YY'); // "Oct 25th 26"
m.fromNow(); // "// Tiempo relativo (ej. hace 3 horas)"
m.calendar(); // "// Formato de calendario"
Tabla de Tokens de Fecha
| Token | Rango de Salida | Descripción |
|---|---|---|
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 |
Tabla de Tokens de Hora
| Token | Rango de Salida | Descripción |
|---|---|---|
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 |
Manipulación de Fechas
Los objetos Moment son mutables. Las operaciones modifican la instancia directamente:
// Sumar y restar tiempo
moment().add(7, 'days');
moment().subtract(1, 'month');
// Ajustar al limite de una unidad
moment().startOf('day'); // 00:00:00.000 hoy
moment().endOf('month'); // 23:59:59.999 ultimo dia del mes
// Clonar para evitar mutaciones accidentales
const original = moment();
const nextWeek = original.clone().add(7, 'days');
Formatos Localizados Predefinidos
| Formato | Ejemplo de Salida |
|---|---|
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 |
Alternativas Modernas
Moment.js esta en modo de mantenimiento. Alternativas modernas recomendadas:
- date-fns: Funciones modulares, inmutables y compatibles con tree-shaking.
- Day.js: Libreria ligera de 2KB con API compatible con Moment.
- Luxon: Libreria moderna de los autores de Moment basada en la API Intl.
- Native
Intl.DateTimeFormat: Nativa en navegadores modernos y Node.js sin dependencias.