Moment.js
Today we were playing with a very useful library for Date handling in javascript called Moment.js. As his description says, Moment.js is a library for Parse, validate, manipulate, and display dates in JavaScript.
From a simple string, with some valid date format, it will create an object (parse), will validate the string and we can add or delete time, reformat the date and do many more manipulations of the date object in order to do a better display of the information.
Instead of modifying the native Date.prototype
, Moment.js creates a wrapper for the Date
object. To get this wrapper object, simply call moment()
with one of the supported input types.
The Moment
prototype is exposed through moment.fn
. If you want to add your own functions, that is where you would put them.
To use it you just need to remember this function
moment();
To get the current date and time, just call moment()
with no parameters.
var now = moment();
This is essentially the same as calling moment(new Date()).
If you want to parse a string you must use it
moment(String);
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, then fall back to new Date(string)
if a known format is not found.
If you have a PHP timstamp you can parse it with Moment.js but before do it multiply the timestamp by 1000 since in JavaScript the timestamp are in milliseconds and in PHP in seconds.
You can find more information about the usage in the library docs.