Use Momentjs for different date formats in Phonegap
Posted By : Avilash Choudhary | 25-Mar-2015
Momentjs is a library which allows different types of methods for dealing with different date formats. you can just download and link the library in index.html to working with momentjs.
To calculate the days difference between two dates, you can use the below code:
var currentDate = moment().format("YYYY-MM-DD”);
var expectedDate = “2015-03-13T07:29:58Z”;
var days = moment(expectedDate).diff(currentDate, 'days');
console.log(“days “+ days);
This function will print the days difference between two dates, if you want to calculate the months or years difference then just changes the second argument in the diff method to ‘months’ or ‘years’.
if you don’t pass the second argument then by default it will return the difference in milliseconds. By default it returns the rounded value if you want floating value then just pass true as third argument in diff method.
moment("2015-03-13T07:29:58Z").diff(“2012-08-13T07:29:58Z", ‘years’,true);
if you want to extract the day and month only from a date then you can use below code
moment(“2015-03-13T07:29:58Z”).format("MMM D”); // Mar 13
moment(“2015-03-13T07:29:58Z").format('ll’) // Mar 13 2015
To print date and time like that Mar 25 2015 1:27 PM then use
moment().format('lll’);
Another format
moment().format(“dddd, MMMM Do YYYY, h:mm:ss a”) // Wednesday, March 25th 2015, 1:30:12 pm
moment().format("MMM. DD, YYYY”); // Mar. 25, 2015
This library provides an easy way of manipulate dates with time. you can easily change in its methods to work according to your needs. There are lots of methods in momentjs. To print day with some text you can use the below code:
moment().format('[Today] dddd’) // Today Wednesday
moment().fromNow() // a few seconds ago
To check if a date is before or after of a particular date then use,
moment(‘2014-10-28’).isBefore(‘2014-11-14’); // true
moment(‘2015-01-28’).isBefore(‘2015-02-15’,’year'); // false
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Avilash Choudhary
Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.