# 安装
Day.js 可以运行在浏览器和 Node.js 中。
本文档所有代码都可以在这两种环境中正常运行,所有单元测试也都在这两个环境下完成。
CI 系统测试覆盖的浏览器有:Chrome on Windows XP, IE 8, 9, and 10 on Windows 7, IE 11 on Windows 10, latest Firefox on Linux, and latest Safari on OSX 10.8 and 10.11。
打开您的浏览器控制台,即可输入测试示例代码。
# Node.js
要在您的 Node.js 项目中使用 Day.js,只需使用 npm (opens new window) 安装
> npm install dayjs
> cnpm install dayjs -S
> yarn add dayjs
> pnpm add dayjs
然后在项目代码中引入即可:
var dayjs = require('dayjs')
// import dayjs from 'dayjs' // ES 2015
dayjs().format()
# 浏览器
<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>
<script>
dayjs().format()
</script>
CDN引入
注意
Day.js可以通过CDN提供商,如:cdnjs.com (opens new window), unpkg (opens new window),jsdelivr (opens new window)和bootcdn.cn (opens new window)等引入
<!-- CDN example (unpkg) -->
<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>
<script>dayjs().format()</script>
# 微信小程序
# 方式1
下载 dayjs.min.js
放到小程序 lib
目录下(没有新建或用其他目录)
引入示例:
const dayjs = require('../../libs/dayjs.min.js');
# 方式2
使用 npm
安装
> npm install dayjs --save
引入示例:
const dayjs = require("dayjs");
# Element-plus
Element-plus (opens new window) 组件库默认支持 dayjs 进行日期时间处理,所以可以直接导入使用,相关 Date Picker (opens new window) 组件介绍。
import { dayjs } from 'element-plus'
// 扩展插件
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
dayjs.extend(isSameOrBefore)
dayjs.extend(isSameOrAfter)
dayjs().isSameOrBefore(dayjs('2011-01-01'))
# Typescript
在 NPM 包中已经包含 Day.js 的 TypeScript 类型定义文件。
通过 NPM 安装
> npm install dayjs --save
在 TypeScript 项目中导入并使用
import * as dayjs from 'dayjs'
dayjs().format()
如果您的 tsconfig.json
包含以下配置,您必须使用 import dayjs from 'dayjs'
的 default import 模式:
{ //tsconfig.json
"compilerOptions": {
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
}
}
如果您没有上述配置,default import 将无法正常工作。 您需要使用 import * as dayjs from 'dayjs'
import * as dayjs from 'dayjs'
# 导入本地化语言和插件
在使用本地化语言和插件,您首先需要导入它们。
import * as dayjs from 'dayjs'
import * as isLeapYear from 'dayjs/plugin/isLeapYear' // 导入插件
import 'dayjs/locale/zh-cn' // 导入本地化语言
dayjs.extend(isLeapYear) // 使用插件
dayjs.locale('zh-cn') // 使用本地化语言
# 下载
访问 https://www.jsdelivr.com/package/npm/dayjs (opens new window) 下载最新版本的 Day.js。
访问 https://github.com/iamkun/dayjs/releases (opens new window) 查看 Day.js 的已发布版本和源代码
解析 →