Quick Tip: Handle Date and Time Like a Boss with moment.js
Cool things you can do with it
The first stop is to create a new moment object. This is done by calling the global moment() function. If you leave it empty, it will use the current time. Otherwise you can pass a timestamp, an array or string with a format that will be parsed into a date.
Create a moment object
// Create a new moment object var now = moment(); // Create a moment in the past, using a string date var m = moment("April 1st, 2005", "MMM-DD-YYYY"); // Create a new moment using an array var m = moment([2005, 3, 1]);
Working with time
// What time is it? console.log(moment().format('HH:mm:ss')); // 16:13:11 // What day of the week is it? var day = moment().day(); // 5 console.log( moment.weekdays[day] ); // Friday // What is the current month name? console.log( moment.months[moment().month()] ); // August // What time is it in London? (time zone: UTC) console.log( moment.utc().format('HH:mm:ss') ); // 13:23:41 // What time is it in Japan? (time zone: UTC+9) console.log( moment.utc().add('hours',9).format('HH:mm:ss') ); // 22:23:41
As you can see, the format method is what you need to turn a moment object into something readable. There are plenty of formatting options to choose from and are easier to remember than what you get in PHP’s date function.
Working with dates
// How old are you? var m = moment("Mar 26th, 1989", "MMM-DD-YYYY"); console.log('You are '+m.fromNow() + ' old'); // You are 23 years ago old // Oops. We better leave the "ago" part out: console.log('You are '+m.fromNow(true) + ' old'); // You are 23 years old // When will the next world cup be? console.log( moment('June 12th, 2014','MMM DD YYYY').fromNow() ); // in 2 years // What will be the date 7 days from now? console.log( moment().add('days',7).format('MMMM Do, YYYY') ); // September 7th, 2012
The fromNow() method is very useful in producing readable time differences. It automatically scales the period it returns from seconds to years.
// Find the duration between two dates var breakfast = moment('8:32','HH:mm'); var lunch = moment('12:52','HH:mm'); console.log( moment.duration(lunch - breakfast).humanize() + ' between meals' ) // 4 hours between meals
The duration method takes a number of milliseconds and creates a new object. By using its humanize() method, we get human readable version.
No time to lose!
I hope that this short overview gave you a good idea of what is possible with moment.js. If you want to learn more, follow the project on github and read through the examples and documentation on their homepage.
Presenting Bootstrap Studio
a revolutionary tool that developers and designers use to create
beautiful interfaces using the Bootstrap Framework.