欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JavaScript日期格式化封装函数

最编程 2024-08-03 20:49:08
...
  1. 常用封装方法
/**
 * splitValue 时间戳 转换
 * @returns {string}
 */

export function formatDate(value) {
  let date = new Date(value);
  let y = date.getFullYear();
  let MM = date.getMonth() + 1;
  MM = MM < 10 ? '0' + MM : MM;
  let d = date.getDate();
  d = d < 10 ? '0' + d : d;
  let h = date.getHours();
  h = h < 10 ? '0' + h : h;
  let m = date.getMinutes();
  m = m < 10 ? '0' + m : m;
  let s = date.getSeconds();
  s = s < 10 ? '0' + s : s;
  return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
}

  1. 高级方法(时间*格式输出)
  • 函数封装
/**
 * splitValue 获取当前时间
 * @param value
 * @returns {array}
 */
export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length)
      );
    }
  }
  return fmt;
}

export default {
  formatDate,
};

  • 文件引入
// 获取格式化时间函数
import {formatDate} from '@/common/filter.js';
  • 组件使用
filters: {
    formatDate(time) {
    var date = new Date(time);
    return formatDate(date, 'yyyy-MM-dd');
   }
},
<div class="time">{{item.XXX| formatDate}}</div>
let nowDate = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');