Moment.js 不容错过的超棒Javascript日期处理类库
主要特性:
- 3.2kb超轻量级
- 独立类库,意味这你不需要倒入一堆js
- 日期处理支持UNIX 时间戳,String,指定格式的Date
- 日期处理:加,减日期
- 日期显示:包括相对时间显示的日期显示选项
- 其它内建的功能,例如,保存,timezone offset和i18n支持
- 可以作为node.js的一个模块
使用:
首先,你可以创建一个新的moment 对象。它通过全局的moment() 方法来完成。如果你不设置参数,它将使用当前的时间。
创建moment 对象
// 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]);
注意:和JavaScript Date() 对象一样,月份是从0开始的,所以3是4月份。
格式化时间
// 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(); //
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
格式化日期
// 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