Moment.js 超棒Javascript日期處理類庫

Moment.js 不容錯過的超棒Javascript日期處理類庫node

主要特性:ide

  1. 3.2kb超輕量級
  2. 獨立類庫,意味這你不須要倒入一堆js
  3. 日期處理支持UNIX 時間戳,String,指定格式的Date
  4. 日期處理:加,減日期
  5. 日期顯示:包括相對時間顯示的日期顯示選項
  6. 其它內建的功能,例如,保存,timezone offset和i18n支持
  7. 能夠做爲node.js的一個模塊 

使用:spa

首先,你能夠建立一個新的moment 對象。它經過全局的moment() 方法來完成。若是你不設置參數,它將使用當前的時間。3d

建立moment 對象

1 // Create a new moment object
2 var now = moment();
3  
4 // Create a moment in the past, using a string date
5 var m = moment("April 1st, 2005", "MMM-DD-YYYY");
6  
7 // Create a new moment using an array
8 var m = moment([2005, 3, 1]);    

注意:和JavaScript Date() 對象同樣,月份是從0開始的,因此3是4月份。code

格式化時間

 1 // What time is it?
 2 console.log(moment().format('HH:mm:ss')); // 16:13:11
 3  
 4 // What day of the week is it?
 5 var day = moment().day(); // 5
 6 console.log( moment.weekdays[day] ); // Friday
 7  
 8 // What is the current month name?
 9 console.log( moment.months[moment().month()] ); // August
10  
11 // What time is it in London? (time zone: UTC)
12 console.log( moment.utc().format('HH:mm:ss') ); // 13:23:41
13  
14 // What time is it in Japan? (time zone: UTC+9)
15 console.log( moment.utc().add('hours',9).format('HH:mm:ss') ); // 22:23:41    
View Code

格式化日期

 1 // How old are you?
 2 var m = moment("Mar 26th, 1989", "MMM-DD-YYYY");
 3  
 4 console.log('You are '+m.fromNow() + ' old'); // You are 23 years ago old
 5  
 6 // Oops. We better leave the "ago" part out:
 7 console.log('You are '+m.fromNow(true) + ' old'); // You are 23 years old
 8  
 9 // When will the next world cup be?
10 console.log( moment('June 12th, 2014','MMM DD YYYY').fromNow() ); // in 2 years
11  
12 // What will be the date 7 days from now?
13 console.log( moment().add('days',7).format('MMMM Do, YYYY') ); // September 7th, 2012   
View Code
相關文章
相關標籤/搜索