230

day.js轻量级处理时间和日期格式化库

 5 years ago
source link: https://www.helloweba.net/javascript/604.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Day.js是一个轻量的处理时间和日期的JavaScript库,和Moment.js的API设计保持完全一样. 如果您曾经用过Moment.js, 那么您已经知道如何使用Day.js。

查看演示

Day.js的特点有:

  • 和 Moment.js 相同的 API 和用法
  • 不可变数据 (Immutable)
  • 支持链式操作 (Chainable)
  • 国际化 I18n
  • 仅 2kb 大小的微型库
  • 全浏览器兼容

安装

使用npm安装:

npm install dayjs --save

API

Day.js 有很多 API 来解析、处理、校验、增减、展示时间和日期。

dayjs('2018-08-08') // 解析
 
dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // 展示
 
dayjs()
  .set('month', 3)
  .month() // 获取
 
dayjs().add(1, 'year') // 处理
 
dayjs().isBefore(dayjs()) // 查询

国际化 I18n

Day.js 支持国际化,但除非手动加载,多国语言默认是不会被打包到工程里的。

import 'dayjs/locale/es' // 按需加载
 
dayjs.locale('es') // 全局使用西班牙语
 
dayjs('2018-05-05')
  .locale('zh-cn')
  .format() // 在这个实例上使用简体中文

插件

插件是一些独立的程序,可以给 Day.js 增加新功能和扩展已有功能。

import advancedFormat from 'dayjs/plugin/advancedFormat' // 按需加载插件
 
dayjs.extend(advancedFormat) // 使用插件
 
dayjs().format('Q Do k kk X x') // 使用扩展后的API

插件列表

该项目的github地址是: https://github.com/iamkun/dayjs


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK