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

js dayjs

作者:枫尘于往逝   发布日期:2025-08-09   浏览:69

// 使用 Day.js 进行日期操作的示例代码

// 首先需要安装 dayjs,可以通过 npm 或 yarn 安装
// npm install dayjs
// 或者
// yarn add dayjs

// 引入 dayjs
const dayjs = require('dayjs');

// 获取当前时间
const now = dayjs();
console.log('当前时间:', now.format()); // 输出格式化后的当前时间

// 获取特定日期的时间
const specificDate = dayjs('2023-10-01');
console.log('特定日期:', specificDate.format());

// 日期加减操作
const tomorrow = now.add(1, 'day');
console.log('明天:', tomorrow.format());

const lastWeek = now.subtract(7, 'day');
console.log('上周同一时间:', lastWeek.format());

// 比较两个日期
const isAfter = now.isAfter(specificDate);
console.log('当前时间是否在特定日期之后:', isAfter);

const isBefore = now.isBefore(specificDate);
console.log('当前时间是否在特定日期之前:', isBefore);

// 格式化日期输出
const formattedDate = now.format('YYYY-MM-DD HH:mm:ss');
console.log('格式化后的日期:', formattedDate);

// 获取两个日期之间的差异
const diffDays = now.diff(specificDate, 'day');
console.log('两个日期相差天数:', diffDays);

解释说明:

  1. 引入 Day.js:通过 require('dayjs') 引入 Day.js 库。
  2. 获取当前时间:使用 dayjs() 获取当前时间,并通过 format() 方法进行格式化输出。
  3. 获取特定日期:通过传递日期字符串给 dayjs() 来获取特定日期。
  4. 日期加减操作:使用 add()subtract() 方法对日期进行增减操作。
  5. 比较两个日期:使用 isAfter()isBefore() 方法来比较两个日期的先后顺序。
  6. 格式化日期输出:通过 format() 方法自定义日期的输出格式。
  7. 获取日期差异:使用 diff() 方法计算两个日期之间的差异,可以指定单位(如天、小时等)。

上一篇:js trimstart

下一篇:js isfinite

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 点击空白区域触发事件

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

Laravel 中文站