dayjs如何获取年月日时分秒
时间: 2025-06-09 22:15:11 浏览: 20
<think>我们使用Day.js库来获取当前时间的年月日时分秒首先确保已经安装了Day.js,如果没有安装,可以通过npminstalldayjs安装,或者通过script标签引入。在代码中,我们首先引入dayjs,然后创建一个dayjs对象,然后使用其提供的方法来获取年、月、日、时、分、秒。注意:月份是从0开始的,所以如果我们需要实际的月份(1-12),需要加1,但是dayjs中获取月份的方法返回的是0-11,因此需要+1。但是,根据Day.js文档,我们可以使用.format()方法来格式化输出,这样更简便。有两种方式:1.分别获取年、月、日、时、分、秒,然后组合。2.使用.format()方法格式化输出。这里我们将展示两种方式。方式一:使用getter方法-.year()获取年份(四位数字)-.month()获取月份(0-11),需要+1得到1-12-.date()获取日期(1-31)-.hour()获取小时(0-23)-.minute()获取分钟(0-59)-.second()获取秒(0-59)方式二:使用.format()格式化-.format('YYYY')四位数的年份-.format('MM')两位数的月份(01-12)-.format('DD')两位数的日期(01-31)-.format('HH')24小时制的两位数小时(00-23)-.format('mm')两位数分钟(00-59)-.format('ss')两位数秒(00-59)下面给出代码示例:</think>
下面详细介绍如何使用 Day.js 获取年月日时分秒信息。Day.js 是一个轻量级处理日期和时间的 JavaScript 库,类似 Moment.js 的 API。
### 解决方案
使用 Day.js 的 `.format()` 方法和专用 getter 方法可以获取各种时间单位。以下是两种常用方式:
#### 方法一:使用 format 方法(推荐)
```javascript
import dayjs from 'dayjs';
const now = dayjs();
// 获取完整日期时间字符串
const datetime = now.format('YYYY-MM-DD HH:mm:ss');
console.log(datetime); // 例:2023-08-15 14:30:45
// 分别获取各时间单位(通过格式化)
const year = now.format('YYYY'); // 四位年份
const month = now.format('MM'); // 两位数月份 (01-12)
const date = now.format('DD'); // 两位数日期 (01-31)
const hour = now.format('HH'); // 24小时制小时 (00-23)
const minute = now.format('mm'); // 分钟 (00-59)
const second = now.format('ss'); // 秒 (00-59)
```
#### 方法二:使用专用 getter 方法
```javascript
import dayjs from 'dayjs';
const now = dayjs();
// 使用专用方法获取各时间单位
const year = now.year(); // 数字年份,如 2023
const month = now.month() + 1; // 月份 (0-11),需 +1 转为实际月份
const date = now.date(); // 日期 (1-31)
const hour = now.hour(); // 小时 (0-23)
const minute = now.minute(); // 分钟 (0-59)
const second = now.second(); // 秒 (0-59)
// 组合成字符串
const customFormat = `${year}-${month.toString().padStart(2, '0')}-${date.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
console.log(customFormat);
```
### 关键说明
1. **`.format()` 方法**
- 使用格式化字符串输出时间:
- `YYYY`:四位年份
- `MM`:两位数月份 (01-12)
- `DD`:两位数日期 (01-31)
- `HH`:24小时制小时 (00-23)
- `mm`:分钟 (00-59)
- `ss`:秒 (00-59)
2. **专用 getter 方法**
- `.year()` → 返回数字年份
- `.month()` → 返回 **0-11** 的月份(需 +1 处理)
- `.date()` → 返回 1-31 的日期
- `.hour()/.minute()/.second()` → 返回对应时间单位数值
- 需要手动补零:`padStart(2, '0')` 确保两位数格式
3. **时区注意**
- 默认使用本地时区
- 可配合 `utc` 插件处理 UTC 时间:
```javascript
import utc from 'dayjs/plugin/utc';
dayjs.extend(utc);
console.log(dayjs().utc().format());
```
### 实时获取示例
```javascript
setInterval(() => {
const current = dayjs();
console.log(`当前时间: ${current.format('HH:mm:ss')}`);
}, 1000);
```
### 推荐用法
对于完整日期时间,**`.format()` 是最简洁的方式**,避免手动处理数字格式转换。当需要单独使用某个时间单位进行计算时,专用 getter 方法更合适。
阅读全文
相关推荐

















