时间组件库Day.js那些事

一、简介

1. 什么是Day.js

Day.js 是一个轻量级,易于使用的 JavaScript 日期库,提供了强大的日期和时间处理功能,与Moment.js的API设计相似,但具有更高的性能和更小的体积。

Day.js官网icon-default.png?t=O83Ahttps://day.js.org/docs/zh-CN/installation/installation

2. 优势

a. 特点

  • 轻量级:Dayjs的压缩后大小只有2KB左右,远小于Moment.js。
  • 可扩展:Dayjs支持通过插件扩展功能,如自定义解析和格式化等。
  • 兼容性:Dayjs兼容大多数浏览器,包括IE10+。

b. Dayjs与Moment对比

  • 性能:Dayjs的性能优于Moment,特别是在大量时间操作的情况下。
  • 体积:Dayjs的体积远小于Moment,有助于减少项目的整体大小。
  • 功能:Moment提供了更丰富的时间日期处理功能,适用于复杂的时间操作需求。
  • 使用场景:Dayjs适用于简单的时间日期处理和性能敏感的项目;Moment适用于复杂的时间操作和国际化的项目。

3. 安装方法(以vue为例)

1.可以通过 npm、yarn 或 cnpm 进行安装

npm install dayjs

yarn add dayjs

cnpm install dayjs -S

2.main.js中配置


import dayjs from 'dayjs'

Vue.prototype.dayjs = dayjs;

二、Day.js基本用法

        // 获取当前时间(返回dayjs对象)
        const currentDayjsObj = dayjs();
        // 输出示例:Dayjs { '$d': 2024-11-27T13:40:18.718Z, '$y': 2024, '$M': 10, '$D': 27, '$h': 13, '$m': 40, '$s': 18, '$ms': 718 }

        // 获取当前时间(返回原生Date对象)
        const currentDateObj = dayjs().toDate();
        // 输出示例:Wed Nov 27 2024 21:40:18 GMT+0800 (中国标准时间)

        // 获取当前时间(年月日时分秒,字符串)
        const currentTimeStrFull = dayjs().format("YYYY-MM-DD HH:mm:ss");
        // 输出示例:2024-11-27 21:40:18

        // 获取当前时间(年月日,字符串)
        const currentTimeStrDateOnly = dayjs().format("YYYY-MM-DD");
        // 输出示例:2024-11-27

        // 获取时间戳 (秒)
        const currentUnixTimestamp = dayjs().unix();
        // 输出示例:1700960418
        // 返回当前时间距离1970年1月1日00:00:00 UTC的秒数

        // 获取时间戳 (毫秒)
        const currentValueOfTimestamp = dayjs().valueOf();
        // 输出示例:1700960418718

        // 获取年
        const currentYear = dayjs().year();
        // 输出示例:2024

        // 获取月
        const currentMonth = dayjs().month();
        // 输出示例:10
        // 返回当前时间对应的月份(注意,在dayjs中月份是从0开始计数,0代表1月,10代表11月)

        // 获取日
        const currentDay = dayjs().date();
        // 输出示例:27

        // 获取时
        const currentHour = dayjs().hour();
        // 输出示例:13

        // 获取分
        const currentMinute = dayjs().minute();
        // 输出示例:40

        // 获取秒
        const currentSecond = dayjs().second();
        // 输出示例:18

        // 获取毫秒
        const currentMillisecond = dayjs().millisecond();
        // 输出示例:718

        // 在日期的基础上加上7天
        const dateAfterAddingDays = dayjs("2024-11-10").add(7, "day");
        // 输出示例:Dayjs { '$d': 2024-11-17T00:00:00.000Z, '$y': 2024, '$M': 10, '$D': 17, '$h': 0, '$m': 0, '$s': 0, '$ms': 0 }

        // 获取当天的开始时间,并格式化
        const startOfDayFormatted = dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss.SSS");
        // 输出示例:2024-11-27 00:00:00.000

        // 获取当天的结束时间,并格式化
        const endOfDayFormatted = dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss.SSS");
        // 输出示例:2024-11-27 23:59:59.999

        // 获取两个日期间的时间差
        const date1 = dayjs("2024-11-27");
        const date2 = dayjs("2024-10-10");
        const diffInDays = date1.diff(date2, "day");
        // 输出示例:48

三、Day.js高级功能

1. 插件机制

Day.js具有高度的可扩展性,通过插件机制可以扩展其功能。以下是一些常用插件:

a. 自定义解析和格式化

Day.js可以通过插件支持自定义解析和格式化:

const customParseFormat = require('dayjs/plugin/customParseFormat');
dayjs.extend(customParseFormat);

const customDate = dayjs('27-07-2024', 'DD-MM-YYYY');
console.log(customDate.format('YYYY-MM-DD')); // 输出:2024-07-27

b. 处理相对时间

使用relativeTime插件处理相对时间:

const relativeTime = require('dayjs/plugin/relativeTime');
dayjs.extend(relativeTime);

const date = dayjs().subtract(3, 'day');
console.log(date.fromNow()); // 输出:3天前

c. 时间区间操作

duration插件可以方便地进行时间区间的操作:

const duration = require('dayjs/plugin/duration');
dayjs.extend(duration);

const dur = dayjs.duration({ hours: 2, minutes: 30 });
console.log(dur.asMinutes()); // 输出:150

2. 国际化支持

Day.js内置了多种语言包,可以方便地切换语言:

const locale = require('dayjs/locale/zh-cn');
dayjs.locale('zh-cn');

const date = dayjs();
console.log(date.format('dddd, MMMM D, YYYY')); // 输出中文格式的日期

四、使用场景

  • 日期格式化显示:在网页应用或者后台管理系统中,需要将日期以特定的格式展示给用户,如水印,在新闻网站上显示文章发布日期,或者在电商平台展示订单日期。
import dayjs from 'dayjs';
const articleDate = dayjs('2024-11-20').format('MMM D, YYYY');
console.log(articleDate); 
// 输出: Nov 20, 2024
  • 日期比较与筛选:在任务管理应用中,比较任务的截止日期和当前日期,以筛选出过期任务或者即将到期的任务。
import dayjs from 'dayjs';
const currentDate = dayjs();
const taskDeadline = dayjs('2024-12-01');
if (taskDeadline.diff(currentDate, 'day') < 0) {
  console.log("任务已过期");
} else if (taskDeadline.diff(currentDate, 'day') <= 3) {
  console.log("任务即将到期");
}
  • 时间区间计算:在项目进度跟踪工具中,计算项目阶段的持续时间。例如,计算一个项目从开始日期到结束日期总共持续了多少天。
import dayjs from 'dayjs';
const projectStart = dayjs('2024-10-01');
const projectEnd = dayjs('2024-11-30');
const projectDuration = projectEnd.diff(projectStart, 'day');
console.log(`项目持续了 ${projectDuration} 天`); 
// 输出: 项目持续了60天
  • 相对时间显示(需插件):在社交应用中,显示消息发送时间为相对时间,如 “3 分钟前”“昨天” 等,让用户更直观地了解消息的时效性。
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
const messageTime = dayjs().subtract(2, 'hour');
console.log(messageTime.fromNow()); 
// 输出: 2 hours ago
  • 日期本地化(需插件):在跨国应用中,根据用户所在地区的语言习惯和日期格式来显示日期。例如,在面向不同国家用户的金融应用中显示交易日期。
import dayjs from 'dayjs';
import 'dayjs/locale/fr';
dayjs.locale('fr');
const transactionDate = dayjs('2024-11-27');
console.log(transactionDate.format('LL')); 
// 输出: 27 novembre 2024(假设在法语环境下格式化日期)

欢迎指正! 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值