【js/ts】将各种时间转换为指定日期格式

本文介绍了一个实用的JavaScript函数,用于将各种时间格式(包括Date对象、时间戳和字符串)转换为指定格式的日期字符串或时间戳。提供了丰富的示例和应用场景,涵盖不同输入格式的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js

/**
 * 将各种时间格式转换为指定格式的日期字符串或时间戳
 * @param {Date|number|string|undefined} time 输入的时间(Date对象、时间戳、日期字符串或分隔符)
 * @param {string} [format='yyyy-MM-dd HH:mm:ss'] 目标日期格式、分隔符或特定字符串('timestamp' 或 'timestamp-seconds')
 * @returns {string|number} 指定格式的日期字符串或时间戳
 */
export function formatDate(time, format = "yyyy-MM-dd HH:mm:ss") {
   
  let date;
  let separator;

  // 如果 time 是 'now',则获取当前时间
  if (time === 'now') {
   
    date = new Date();
  } else if (typeof time === 'string' && time.length === 1) {
   
    date = new Date();
    separator = time;
    format = `yyyy${
     separator}MM${
     separator}dd HH:mm:ss`;
  } else if (time === undefined && format.length === 1) {
   
    date = new Date();
    separator = format;
    format = `yyyy${
     separator}MM${
     separator}dd HH:mm:ss`;
  } else {
   
    date = time instanceof Date ? time : new Date(time);
    if (isNaN(date.getTime())) throw new Error("Invalid date");
  }

  // 处理特殊格式要求
  if (format === 'timestamp') {
   
    return date.getTime(); // 返回毫秒级时间戳
  }
  if (format === 'timestamp-seconds') {
   
    return Math.floor
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

★雨 潇★

谢谢您的鼓励,我会继续努力的~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值