Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

实现日期格式化函数

Sunny-117 opened this issue · comments

commented
实现日期格式化函数
commented
function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

console.log(parseTime(Date.now()));
console.log(parseTime(Date.now(), "{y}-{m}-{d}"));

image

function getFormatTime(formmat) { let time = new Date() let day = time.getDate() let month = time.getMonth() + 1 let year = time.getFullYear() let hour = time.getHours() let minute = time.getMinutes() let seconds = time.getSeconds() let empty = ' ' switch (formmat) { case 'yyyy-mm-dd': return${year}-${month}-${day}; case 'yyyy-mm-dd hh:mm:ss': return ${year}-${month}-${day}${empty}${hour}:${minute}:${seconds}; case 'yyyy年mm月dd日hh时mm分ss秒': return ${year}年${month}月${day}日${hour}时${minute}分${seconds}秒} }

commented
function formatTime() {
  const time = new Date();
  const year = time.getFullYear();
  const month = time.getMonth() + 1;
  const day = time.getDate();
  const hour = time.getHours();
  const minute = time.getMinutes();
  const seconds = time.getSeconds();
  return `${year}-${month}-${day} ${hour}:${minute}:${seconds}`;
}
console.log(formatTime());

最简易版本的,注意 没有加0的版本
格式:年-月-日 时:分:秒

function formatDate(date, format) {
    const pad = (n) => n < 10 ? '0' + n : n;
    const dateDict = {
        "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, matched => dateDict[matched]);
}
let date = new Date();
console.log(formatDate(date, 'YYYY-MM-DD')); // 输出形如 '2023-09-08' 的日期
console.log(formatDate(date, 'YYYY/MM/DD HH:mm:ss')); // 输出形如 '2023/09/08 17:20:04'