// 使用 Day.js 获取当前日期并格式化输出
const dayjs = require('dayjs'); // 引入 dayjs 库
// 示例 1: 获取当前日期和时间
const now = dayjs(); // 获取当前日期和时间
console.log(now.format()); // 输出格式化的当前日期和时间,例如:2023-10-05T14:48:32+08:00
// 示例 2: 格式化日期
const formattedDate = now.format('YYYY-MM-DD'); // 格式化为年-月-日
console.log(formattedDate); // 输出:2023-10-05
// 示例 3: 添加或减去天数、月份等
const nextWeek = now.add(7, 'day'); // 当前日期加7天
console.log(nextWeek.format('YYYY-MM-DD')); // 输出:2023-10-12
const lastMonth = now.subtract(1, 'month'); // 当前日期减去1个月
console.log(lastMonth.format('YYYY-MM-DD')); // 输出:2023-09-05
// 示例 4: 比较两个日期
const anotherDate = dayjs('2023-10-01');
const isAfter = now.isAfter(anotherDate); // 判断当前日期是否在 anotherDate 之后
console.log(isAfter); // 输出:true
const isSameDay = now.isSame(anotherDate, 'day'); // 判断两个日期是否是同一天
console.log(isSameDay); // 输出:false
// 示例 5: 设置特定的日期或时间
const specificDate = dayjs().set('year', 2024).set('month', 5).set('date', 20); // 设置为 2024 年 6 月 20 日
console.log(specificDate.format('YYYY-MM-DD')); // 输出:2024-06-20
require('dayjs') 引入 Day.js 库。dayjs() 可以获取当前的日期和时间,默认返回的是一个 Day.js 对象。.format() 方法可以将日期格式化为指定的字符串格式。.add() 和 .subtract() 方法可以在日期上添加或减去天数、月份等。.isAfter()、.isBefore() 和 .isSame() 等方法可以比较两个日期之间的关系。.set() 方法可以设置具体的年份、月份或日期。上一篇:js 运算符优先级
下一篇:js unicode编码转换中文
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站