js 时间戳格式化 年月日十分秒

本文介绍了一个实用的时间格式化函数,该函数可以根据不同的参数灵活地返回多种格式的时间字符串,适用于前端开发中对时间显示的需求。

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

// 时间格式化
function dateFormat(timeStamp, type) {
  // 时间格式化
  let time = new Date(timeStamp);

  let YYYY = time.getFullYear();
  let MM = (time.getMonth() + 1) < 10 ? ("0" + (time.getMonth() + 1)) : (time.getMonth() + 1);
  let DD = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
  let hh = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
  let mm = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
  let ss = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();

  let dateType = type.trim() || type;
  switch (dateType) {
    case "YYYY":
      return YYYY;
      break;
    case "YYYYMM":
      return YYYY + "-" + MM;
      break;
    case "YYYYMMDD":
      return YYYY + "-" + MM + "-" + DD;
      break;
    case "YYYYMMDD hh":
      return YYYY + "-" + MM + "-" + DD + " " + hh;
      break
    case "YYYYMMDD hhmm":
      return YYYY + "-" + MM + "-" + DD + " " + hh + ":" + mm;
      break
    case "YYYYMMDD hhmmss":
      return YYYY + "-" + MM + "-" + DD + " " + hh + ":" + mm + ":" + ss;
      break
    case "hh":
      return hh;
      break
    case "hhmm":
      return hh + ":" + mm;
      break
    case "hhmmss":
      return hh + ":" + mm + ":" + ss;
      break
    case "mmss":
      return mm + ":" + ss;
      break
    case "ss":
      return ss;
      break
    default:
      return "时间类型错误,请检查!"

  }
}

如有问题还请指正

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值