How to return the current timestamp with Moment.js?

Here you are assigning an instance of momentjs to CurrentDate: var CurrentDate = moment(); Here just a string, the result from default formatting of a momentjs instance: var CurrentDate = moment().format(); And here the number of seconds since january of… well, unix timestamp: var CurrentDate = moment().unix(); And here another string as ISO 8601 (What’s … Read more

How do I set a mock date in Jest?

As of Jest 26 this can be achieved using “modern” fake timers without needing to install any 3rd party modules: https://jestjs.io/blog/2020/05/05/jest-26#new-fake-timers jest .useFakeTimers() .setSystemTime(new Date(‘2020-01-01’)); If you want the fake timers to be active for all tests, you can set timers: ‘modern’ in your configuration: https://jestjs.io/docs/configuration#timers-string EDIT: As of Jest 27 modern fake timers is … Read more

Parse string to date with moment.js

I always seem to find myself landing here only to realize that the title and question are not quite aligned. If you want a moment date from a string: const myMomentObject = moment(str, ‘YYYY-MM-DD’) From moment documentation: Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object. If you instead want … Read more

How do I change the language of moment.js?

You need moment.lang (WARNING: lang() is deprecated since moment 2.8.0, use locale() instead): moment.lang(“de”).format(‘LLL’); http://momentjs.com/docs/#/i18n/ As of v2.8.1, moment.locale(‘de’) sets the localization, but does not return a moment. Some examples: var march = moment(‘2017-03’) console.log(march.format(‘MMMM’)) // ‘March’ moment.locale(‘de’) // returns the new locale, in this case ‘de’ console.log(march.format(‘MMMM’)) // ‘March’ still, since the instance was … Read more

Get the time difference between two datetimes

This approach will work ONLY when the total duration is less than 24 hours: var now = “04/09/2013 15:00:00”; var then = “04/09/2013 14:20:30″; moment.utc(moment(now,”DD/MM/YYYY HH:mm:ss”).diff(moment(then,”DD/MM/YYYY HH:mm:ss”))).format(“HH:mm:ss”) // outputs: “00:39:30” If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal. If you want … Read more

How do I format a date as ISO 8601 in moment.js?

moment().toISOString(); // or format() – see below http://momentjs.com/docs/#/displaying/as-iso-string/ Update Based on the answer: by @sennet and the comment by @dvlsg (see Fiddle) it should be noted that there is a difference between format and toISOString. Both are correct but the underlying process differs. toISOString converts to a Date object, sets to UTC then uses the … Read more