Skip to content

Instantly share code, notes, and snippets.

@founddrama
Created March 24, 2012 12:53
Show Gist options
  • Save founddrama/2182389 to your computer and use it in GitHub Desktop.
Save founddrama/2182389 to your computer and use it in GitHub Desktop.
Moment.js examples
// node:
var moment = require('moment');
moment().add('days', 2).fromNow();
// 'in 2 days'
moment().subtract('days', 2).fromNow();
// '2 days ago'
moment('November 1977').fromNow()
// '34 years ago'
moment().add('days', 2).calendar();
// 'Monday at 8:30 AM'
moment().subtract('days', 2).calendar();
// 'last Thursday at 8:30 AM'
moment('1977-08-20 14:29:00 UTC').format('MMM. d, YYYY');
// 'Aug. 5, 1977'
moment('1977-08-20 14:29:00 UTC').fromNow();
// 'il y a 35 années'
<html>
<head>
<title>in a Moment.js</title>
</head>
<body>
<h1>Moment.js here now: <span id="then" data-date="Sat Mar 24 2012 08:42:14 GMT-0400 (EDT)"></span></h1>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="/js/moment.js"></script>
<script>
$(document).ready(function(){
var then = $('#then'),
date = moment(new Date(then.attr('data-date'))),
update = function(){
then.html(date.fromNow());
};
update();
setInterval(update, 60000);
});
</script>
</body>
</html>
@aidanxyz
Copy link

Thanks! I thought the update functionality is built in.

@ijmorgado
Copy link

Thank you! The second one example helped me a lot 👍

@setkyar
Copy link

setkyar commented Jul 31, 2014

If we want to add dates on moment so we can do like that

moment().add('days', 10).format('YYYY-MM-DD');

It will be add 10 from current date 😄

Thanks for your quick tip 👍

@mauriciosoares
Copy link

Thanks for the examples! I found what I needed here. 👍

@songqinghe
Copy link

mark

@guisouza
Copy link

tks ! =]

@sagardafle
Copy link

How can I pass parameters to moment js ?

var a = moment('2016-06-06T21:03:55');//now
var b = moment('2016-05-06T20:03:55');

console.log(a.diff(b, 'minutes')) // 44700
console.log(a.diff(b, 'hours')) // 745
console.log(a.diff(b, 'days')) // 31
console.log(a.diff(b, 'weeks')) // 4

This works fine .

When when I am trying to do

console.log("from_url "+from_url); //prints: 2016-05-03T10:00:00
var a = moment(from_url);
console.log("a "+a); //prints : 1462294800000 isntead of 2016-05-03T10:00:00

Please help me out. It is kinda urgent.
Thanks.

@brocktriplets
Copy link

This example:
moment('1977-08-20 14:29:00 UTC').format('MMM. d, YYYY');

The 'd' should be 'D' to give Aug, 20, 1977

@sumantapaul
Copy link

I have to make a time difference between server time (Netherlands) and local. I have to check 24 laps time after last modification. How can I convert current client side time to Netherlands time so that I can check difference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment