网站公告

本次更新:新公告样式

详细教程:vitepress.yiov.top

QQ 频道:******(无效二维码)

Skip to content

subtractTime减少时间

更新: 1970/1/1 字数: 0 字 时长: 0 分钟

说明

subtractTime 函数用于从给定的基准时间中减去指定的时间量,并返回计算后的时间。此函数是通过调用 addTime 函数并传递负值实现的。

函数签名

js
/**
 * 减少时间
 * @param {string|number|Date} time - 基准时间
 * @param {number} amount - 要减少的时间量
 * @param {string} unit - 时间单位(年、月、日、小时、分钟、秒)
 * @returns {Date} - 计算后的时间
 */
export function addTime(time, amount, unit)

参数

参数说明

参数说明类型可选值默认值
time基准时间string / number / Date
amount添加的时间量number
unit时间单位string'年' / '月' / '日' / '天' / '小时' / '分钟' / '秒'

返回值

  • Date:计算后的时间,以 Date 对象形式返回。

示例

基本用法

js
import { subtractTime } from 'uviewos';

// 从当前时间中减去 5 天
const newDate = subtractTime(new Date(), 5, '天');
console.log(newDate);
// 输出: 当前时间减去 5 天的日期

添加年、月、小时、分钟、秒等

js
import { subtractTime } from 'uviewos';

// 从当前时间中减去 2 年
const newDateYear = subtractTime(new Date(), 2, '年');
console.log(newDateYear);
// 输出: 当前时间减去 2 年的日期

// 从当前时间中减去 3 个月
const newDateMonth = subtractTime(new Date(), 3, '月');
console.log(newDateMonth);
// 输出: 当前时间减去 3 个月的日期

// 从当前时间中减去 10 小时
const newDateHour = subtractTime(new Date(), 10, '小时');
console.log(newDateHour);
// 输出: 当前时间减去 10 小时的日期
// 从当前时间中减去 15 分钟
const newDateMinute = subtractTime(new Date(), 15, '分钟');
console.log(newDateMinute);
// 输出: 当前时间减去 15 分钟的日期

// 从当前时间中减去 45 秒
const newDateSecond = subtractTime(new Date(), 45, '秒');
console.log(newDateSecond);
// 输出: 当前时间减去 45 秒的日期

错误处理

js
import { subtractTime } from 'uviewos';

try {
  // 尝试减去无效的时间单位
  const invalidDate = subtractTime(new Date(), 5, '周');
} catch (error) {
  console.error(error.message);
  // 输出: 无效的单位
}

Released under the MIT License.

本站访客数 人次 本站总访问量