大家好,最近有接觸nodejs,發現nodejs有一個最大的特點,就是他是使用 javascript 開發的,可以說是一種 script 語言。
好處是說,擁有 javascript 的優點,而且可以通用 javascript 的函式庫,例如我要介紹的 monent 就是一個好例子

網址:
也就說,當你載入 這個函式庫,可以在網頁使用,也可以在 nodejs使用,是不是很方便呢?

那為什麼會載入這個 函式庫來用呢? 主要是因為 javascript 原本的時間物件實在是不好用,所以使用這 monent 比較方便且功能完整。
例如:
//取得明天日期 //原本javascript : var nowDateObj = new Date();//目前時間 nowDateObj.setDate(nowDateObj.getDate() + 1);//增加一天 var day = nowDateObj.getDate();//取得日 var month = nowDateObj.getMonth()+1;//取得月 var year = nowDateObj.getFullYear();//取得年 alert('明天是 '+year+'年'+month+'月'+day+'日'); //在 monent : alert(moment().add(1, 'days').format('明天是 YYYY年MM月DD日'));
主要是用到 add 與 format 功能
這都是原本 javascript 的 Date 參數沒有的功能
日期參數:
Key | Shorthand |
---|---|
years | y |
quarters | Q |
months | M |
weeks | w |
days | d |
hours | h |
minutes | m |
seconds | s |
milliseconds | ms |
這邊我介紹幾個基本用法
//取得今天日期 alert(moment().format('今天是 YYYY年MM月DD日')); //取得明天日期 alert(moment().add(1, 'days').format('明天是 YYYY年MM月DD日')); //取得昨天日期 alert(moment().add(-1, 'days').format('昨天是 YYYY年MM月DD日')); //今年第一天是禮拜幾? alert(moment().startOf('year').format('今年第一天是 e日')); //今年最後一天是禮拜幾? alert(moment().endOf('year').format('今年第一天是 e日')); //取得這個月有幾天 alert(moment().endOf('month').format('這個月有DD日')); //取得下個月月份 alert(moment().add(1, 'months').format('下個月是 YYYY年MM月')); //驗證日期是否正確 alert('2016-11-31'+(moment('2016-11-31').isValid() ? '是':'不是')+'正確日期'); alert('2016-11-30'+(moment('2016-11-30').isValid() ? '是':'不是')+'正確日期');
基本上有這些用法
給大家參考囉
感恩
留言板
歡迎留下建議與分享!希望一起交流!感恩!