Moment CheatSheet

JS
S
JavaScript

Moment JS Snippets. Updated regularly.

1const moment = require('moment');
2
3// Full day time window
4const start = new moment().startOf('day').toDate(); //2017-11-09T00:00:00.000Z
5const end = new moment().endOf('day').toDate(); // 2017-11-09T23:59:59.999Z
6
7// Adding and Subtracting
8const sevenDaysEarlier = moment().subtract(7,'d').endOf('day');
9
10// Formatting
11public today = moment().format('DD/MM/YYYY');
12
13// Month Name
14 public monthName = moment().utc().format('MMMM');
15
16// Start and EndofDay ignoring timezone
17const from = moment.utc(request.query.from, 'DD-MM-YY').startOf('day').toISOString();
18const to = moment.utc(request.query.to, 'DD-MM-YY').endOf('day').toISOString();
19
20// Number of days between 2 dates
21var a = moment([2007, 0, 29]);
22var b = moment([2007, 0, 28]);
23a.diff(b, 'days')+1   //2
24
25// Add a day
26var b = moment().add(1, 'day');
27
28// Generate all months list
29const monthsSelect = moment.monthsShort();
30

Created on 11/9/2017