Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

dayjs api

作者:堕魂灭天   发布日期:2026-01-08   浏览:11

// 使用 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

解释说明:

  1. 引入 Day.js:首先需要通过 require('dayjs') 引入 Day.js 库。
  2. 获取当前日期和时间:使用 dayjs() 可以获取当前的日期和时间,默认返回的是一个 Day.js 对象。
  3. 格式化日期:通过 .format() 方法可以将日期格式化为指定的字符串格式。
  4. 添加或减去时间:使用 .add().subtract() 方法可以在日期上添加或减去天数、月份等。
  5. 比较日期:使用 .isAfter().isBefore().isSame() 等方法可以比较两个日期之间的关系。
  6. 设置特定日期或时间:使用 .set() 方法可以设置具体的年份、月份或日期。

上一篇:js 运算符优先级

下一篇:js unicode编码转换中文

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站