Get the difference between two dates using Moment.js

Let's assume that we want to print the difference between two dates using moment.js:

javascript
// Defining date
const date  = [20, 'June', 2020];

// Splitting day, month and year
const day   = date[0];
const month = date[1];
const year  = date[2];

// Defining two moments
const published = moment().year(year).month(month).date(day);
const now       = moment();

// Getting difference
let difference = now.diff(published, 'days');

// Print difference
console.log(difference);
// 9

To do it using a spanish date:

javascript
import moment from 'moment';
import 'moment/locale/es';

// Defining date
const date  = [20, 'Junio', 2020];

// Splitting day, month and year
const day   = date[0];
const month = date[1];
const year  = date[2];

// Defining two moments
const published = moment().locale('es').year(year).month(month).date(day);
const now       = moment();

// Getting difference
let difference = now.diff(published, 'days');

// Print difference
console.log(difference);
// 9

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.