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

20 篇文章 0 订阅

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;

  // 检查是否只传入了分隔符
  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(date.getTime() / 1000);
  }

  const pad = (num) => String(num).padStart(2, "0");
  const formats = {
    yyyy: date.getFullYear(),
    MM: pad(date.getMonth() + 1),
    dd: pad(date.getDate()),
    HH: pad(date.getHours()),
    mm: pad(date.getMinutes()),
    ss: pad(date.getSeconds()),
  };

  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match) => formats[match]);
}

ts

/**
 * 将各种时间格式转换为指定格式的日期字符串或时间戳
 * @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?: Date | number | string, format: string = "yyyy-MM-dd HH:mm:ss"): string | number {
  let date: Date;
  let separator: string;

  // 检查是否只传入了分隔符
  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 as string | number | Date);
    if (isNaN(date.getTime())) throw new Error("Invalid date");
  }

  // 处理特殊格式要求
  if (format === 'timestamp') {
    return date.getTime();
  }
  if (format === 'timestamp-seconds') {
    return Math.floor(date.getTime() / 1000);
  }

  const pad = (num: number): string => String(num).padStart(2, "0");
  const formats: { [key: string]: string | number } = {
    yyyy: date.getFullYear(),
    MM: pad(date.getMonth() + 1),
    dd: pad(date.getDate()),
    HH: pad(date.getHours()),
    mm: pad(date.getMinutes()),
    ss: pad(date.getSeconds()),
  };

  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match: string): string => formats[match].toString());
}

页面使用

// 示例1:使用当前日期和时间
console.log(formatDate(new Date()));
// 输出: '2023-05-20 15:30:45' (具体时间会根据运行时的当前时间而变)

// 示例2:使用毫秒级时间戳
console.log(formatDate(1621497600000, 'yyyy-MM-dd'));
// 输出: '2021-05-20'

// 示例3:使用秒级时间戳
console.log(formatDate(1621497600, 'MM/dd/yyyy HH:mm'));
// 输出: '05/20/2021 12:00'

// 示例4:使用日期字符串,并自定义输出格式
console.log(formatDate('2024-08-05 02:58:02', 'yyyy年MM月dd日 HH时mm分'));
// 输出: '2024年08月05日 02时58分'

// 示例1:使用当前日期和时间
console.log(formatDate(new Date()));
// 输出: '2023-05-20 15:30:45' (具体时间会根据运行时的当前时间而变)

// 示例2:使用毫秒级时间戳
console.log(formatDate(1621497600000, 'yyyy-MM-dd'));
// 输出: '2021-05-20'

// 示例3:使用秒级时间戳
console.log(formatDate(1621497600, 'MM/dd/yyyy HH:mm'));
// 输出: '05/20/2021 12:00'

// 示例4:使用日期字符串,并自定义输出格式
console.log(formatDate('2024-08-05 02:58:02', 'yyyy年MM月dd日 HH时mm分'));
// 输出: '2024年08月05日 02时58分'

// 示例5:只输出年月
console.log(formatDate('2024-08-05', 'yyyy-MM'));
// 输出: '2024-08'

// 示例6:处理不同的输入格式
console.log(formatDate('August 5, 2024', 'dd/MM/yyyy'));
// 输出: '05/08/2024'

// 示例7:使用不同的分隔符
console.log(formatDate(1621497600000, 'yyyy.MM.dd HH:mm:ss'));
// 输出: '2021.05.20 12:00:00'

formatDate("/") // 返回 "2023/05/15 14:30:45"
formatDate("-") // 返回 "2023-05-15 14:30:45"

console.log(formatDate(date, 'timestamp')); // 1684581000000 (毫秒级时间戳)
console.log(formatDate(date, 'timestamp-seconds')); // 1684581000 (秒级时间戳)
// 示例8:错误处理
try {
  console.log(formatDate('Invalid Date'));
} catch (error) {
  console.log('Error:', error.message);
}
// 输出: 'Error: Invalid date'

ps:在部分 iOS 下无法正常使用,iOS 只支持 “yyyy/MM/dd”、“yyyy/MM/dd HH:mm:ss”、“yyyy-MM-dd”、“yyyy-MM-ddTHH:mm:ss”、“yyyy-MM-ddTHH:mm:ss+HH:mm” 的格式

在这里插入图片描述
感谢你的阅读,如对你有帮助请收藏+关注!
只分享干货实战精品从不啰嗦!!!
如某处不对请留言评论,欢迎指正~
博主可收徒、常玩QQ飞车,可一起来玩玩鸭~

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

★雨 潇★

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

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

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

打赏作者

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

抵扣说明:

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

余额充值