【开源】处理时间和日期的JavaScript库:moment.js

笔者曾经在不止一个软件的开发中碰到日期和时间的问题,特别是一些对时间敏感的流程相关软件。与此同时,日期和时间问题成为本地化的困扰因素之一。

Moment.js几乎解决所有这些问题,无论是操作、验证、解析还是格式化日期或时间(Parse, validate, manipulate, and display dates and times in JavaScript.)。

moment.js的文件大小压缩后为18.1k。

moment.js的网址:https://momentjs.com/

用法示例

Frenchmoment.locale('fr');

relativeTimeOfPostInFrench = moment([2019, 07, 13]).fromNow(); 

 

Format Dates

moment().format('MMMM Do YYYY, h:mm:ss a');
moment().format('dddd');
moment().format("MMM Do YY");
moment().format('YYYY [escaped] YYYY');
moment().format();

Relative Time

moment("20111031", "YYYYMMDD").fromNow();
moment("20120620", "YYYYMMDD").fromNow();
moment().startOf('day').fromNow();
moment().endOf('day').fromNow();
moment().startOf('hour').fromNow();

Calendar Time

moment().subtract(10, 'days').calendar();
moment().subtract(6, 'days').calendar();
moment().subtract(3, 'days').calendar();
moment().subtract(1, 'days').calendar();
moment().calendar();
moment().add(1, 'days').calendar();
moment().add(3, 'days').calendar();
moment().add(10, 'days').calendar();

Multiple Locale Support

moment.locale();
moment().format('LT');
moment().format('LTS');
moment().format('L');
moment().format('l');
moment().format('LL');
moment().format('ll');
moment().format('LLL');
moment().format('lll');
moment().format('LLLL');
moment().format('llll');