moment介绍

Node.jsnpm install moment

1
var moment = require('moment'); moment().format();

注意:在 2.4.0 版本中,全局导出的 moment 对象是不建议使用的。这将在下一主要版本中被删除。
浏览器

1
<script src="moment.js"></script>
<script> moment().format(); </script>

Moment.js 可以通过 cdnjs.com 获得,但要记住,可以通过合并JS文件尽量减少HTTP请求。
Bower
bower install –save moment

需要注意的文件是 moment.js, locale/*.js 和 min/moment-with-locales.js。

1
Require.jsrequire.config({ paths: { "moment": "path/to/moment", } });
define(["moment"], function (moment) { moment().format(); });

meteormeteor / atmosphere / momentjs:moment
meteor add momentjs:moment

http://momentjs.com/downloads/moment.js
http://momentjs.com/downloads/moment.min.js

带有 locales 的文件
http://momentjs.com/downloads/moment-with-locales.js
http://momentjs.com/downloads/moment-with-locales.min.js

通过包管理器下载
bower install moment –save # bower
npm install moment –save # npmInstall-Package Moment.js # NuGet
spm install moment –save # spm
meteor add momentjs:moment # meteor

如何使用格式化日期

1
moment().format('MMMM Do YYYY, h:mm:ss a');
//=>  September 8th 2015, 9:45:36 pm
moment().format('dddd');
//=> Tuesday
moment().format("MMM Do YY");
//=> Sep 8th 15
moment().format('YYYY [escaped] YYYY');
//=> 2015 escaped 2015
moment().format();
//=> 2015-09-08T21:46:43+08:00

相对时间

1
moment("20111031", "YYYYMMDD").fromNow();
//=> 4 years ago
moment("20120620", "YYYYMMDD").fromNow();
//=>3 years ago
moment().startOf('day').fromNow();
//=>a day ago
moment().endOf('day').fromNow();
//=>in 2 hours
moment().startOf('hour').fromNow();
//=>an hour ago

日历时间

1
moment().subtract(10, 'days').calendar();
//=>08/29/2015
moment().subtract(6, 'days').calendar();
//=>Last Wednesday at 9:50 PM
moment().subtract(3, 'days').calendar();
//=>Last Saturday at 9:50 PM
moment().subtract(1, 'days').calendar();
//=>Yesterday at 9:50 PM
moment().calendar();
//=>Today at 9:50 PM
moment().add(1, 'days').calendar();
//=>Tomorrow at 9:51 PM
moment().add(3, 'days').calendar();
//=>Friday at 9:51 PM
moment().add(10, 'days').calendar();
//=>09/18/2015

多语言支持Moment.js 拥有强大的国际化支持。你可以加载多个本地化文件并且在他们之间轻易切换。除了指定全局区域外,还可以给某个特定的 moment 实例指定一个区域。
全局更改区域

1
// 从 2.8.1 开始
moment.locale(String);
moment.locale(String[]);
moment.locale(String, Object);
// 在 2.8.1 中不建议使用
moment.lang(String);
moment.lang(String[]);
moment.lang(String, Object);

更多文档请查看:http://momentjs.com/docs