tk挠痒痒网址发布页-秘密武器
历史搜索

js 日期格式化代码

游客2025-05-16 11:28:01

分享一个前端实用的 js 日期格式化代码,相当给力。

export function getFillDate(key) {
  if(key < 10) {
    return `0${key}`;
  }else{
    return `${key}`;
  }
}
/**
 * 时间戳转化为年月日
 * @param times 时间戳
 * @param ymd 格式类型(yyyy-mm-dd,yyyy/mm/dd)
 * @param hms 可选,格式类型(hh,hh:mm,hh:mm:ss)
 * @returns {年月日}
 */
export function dateFomat (times, ymd,  hms) {
  const oDate = new Date(times)
  const oYear = oDate.getFullYear()
  const oMonth = oDate.getMonth() + 1
  const oDay = oDate.getDate()
  const oHour = oDate.getHours()
  const oMin = oDate.getMinutes()
  const oSec = oDate.getSeconds()
  let oTime // 最后拼接时间
  // 年月日格式
  switch (ymd) {
    case 'yyyy-mm-dd':
      oTime = oYear + '-' + getFillDate(oMonth) + '-' + getFillDate(oDay)
      break
    case 'yyyy/mm/dd':
      oTime = oYear + '/' + getFillDate(oMonth) + '/' + getFillDate(oDay)
      break
  }
  // 时分秒格式
  switch (hms) {
    case 'hh':
      oTime = oTime + ' ' + getFillDate(oHour)
      break
    case 'hh:mm':
      oTime = oTime + ' ' + getFillDate(oHour) + ':' + getFillDate(oMin)
      break
    case 'hh:mm:ss':
      oTime = oTime + ' ' + getFillDate(oHour) + ':' + getFillDate(oMin) + ':' + getFillDate(oSec)
      break
  }
  return oTime
}

js 日期格式化代码 1

标签:js相关

本文是由用户"游客"发布,所有内容的版权归原作者所有。没有经过书面许可,任何单位或个人不得以任何形式复制、转载、引用本网站的内容。否则将追究法律责任。

相关专题