DayJS使用

448 阅读2分钟
import dayjs from "dayjs";

// 1. 获取当前日期
const currentDate = dayjs();
console.log(currentDate.format('YYYY-MM-DD')); // 输出当前日期,如:2024-04-30

// 2. 获取当前时间
const currentTime = dayjs();
console.log(currentTime.format('HH:mm:ss')); // 输出当前时间,如:14:30:00

// 3. 获取指定日期
const specifiedDate = dayjs('2023-01-15');
console.log(specifiedDate.format('YYYY-MM-DD')); // 输出指定日期,如:2023-01-15

// 4. 格式化日期
const formattedDate = dayjs('2024-04-30');
console.log(formattedDate.format('dddd, MMMM D, YYYY')); // 输出格式化后的日期,如:Saturday, April 30, 2024

// 5. 添加/减去时间
const addedTime = dayjs().add(7, 'days');
console.log(addedTime.format('YYYY-MM-DD')); // 输出添加 7 天后的日期,如:2024-05-07

// 6. 计算两个日期之间的差值
const date1 = dayjs('2024-01-01');
const date2 = dayjs('2024-02-01');
const diffInDays = date2.diff(date1, 'days');
console.log(diffInDays); // 输出两个日期之间的天数差,如:31

// 7. 检查日期是否在某个范围内
const targetDate = dayjs('2024-04-30');
const startDate = dayjs('2024-04-01');
const endDate = dayjs('2024-05-01');
const isWithinRange = targetDate.isBetween(startDate, endDate);
console.log(isWithinRange); // 输出 true,因为目标日期在范围内

// 8. 获取一周中的第几天
const dayOfWeek = dayjs().day();
console.log(dayOfWeek); // 输出今天是一周中的第几天,0 表示星期日,1 表示星期一,依此类推

// 9. 获取月份的天数
const daysInMonth = dayjs('2024-02-01').daysInMonth();
console.log(daysInMonth); // 输出该月份的天数,如:29

// 10. 获取两个日期之间的所有日期
const startDate = dayjs('2024-04-01');
const endDate = dayjs('2024-04-05');
const allDates = [];
let currentDate = startDate;
while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {
    allDates.push(currentDate.format('YYYY-MM-DD'));
    currentDate = currentDate.add(1, 'day');
}
console.log(allDates); // 输出包含所有日期的数组,如:['2024-04-01', '2024-04-02', '2024-04-03', '2024-04-04', '2024-04-05']