时间类型的封装(时间戳)

后台返回时间戳,我们可以调用这个函数方法返回不同格式的时间

/**
 * 按类型格式化日期
 * @param {number | Date} date 具体日期变量
 * @param {string} dateType 需要返回类型
 * @return {string} dateText 返回为指定格式的日期字符串
 */
export function getFormatDate  (date, dateType) {
  let dateObj = new Date(date);
  let month = dateObj.getMonth() + 1;
  let strDate = dateObj.getDate();
  let hours = dateObj.getHours();
  let minutes = dateObj.getMinutes();
  let seconds = dateObj.getSeconds();
  if (month >= 1 && month <= 9) {
    month = '0' + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate;
  }
  if (hours >= 0 && hours <= 9) {
    hours = '0' + hours;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = '0' + minutes;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = '0' + seconds;
  }

  let dateText = dateObj.getFullYear() + '年' + (dateObj.getMonth() + 1) + '月' + dateObj.getDate() + '日';
  if (dateType == 'yyyy-mm-dd') {
    dateText = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dateObj.getDate();
  }
  if (dateType == 'yyyy.mm.dd') {
    dateText = dateObj.getFullYear() + '.' + (dateObj.getMonth() + 1) + '.' + dateObj.getDate();
  }
  if (dateType == 'yyyy-mm-dd HH:mm:ss') {
    dateText = dateObj.getFullYear() + '-' + month + '-' + strDate + ' ' + hours + ':' + minutes + ':' + seconds;
  }
  if (dateType == 'mm-dd HH:mm:ss') {
    dateText = month + '-' + strDate + ' ' + hours + ':' + minutes + ':' + seconds;
  }
  if (dateType == 'yyyy年mm月dd日 HH:mm:ss') {
    dateText = dateObj.getFullYear() + '年' + month + '月' + strDate + '日' + ' ' + hours + ':' + minutes + ':' + seconds;
  }
  if (dateType == 'yyyy年mm月dd日 HH:mm') {
    dateText = dateObj.getFullYear() + '年' + month + '月' + strDate + '日' + ' ' + hours + ':' + minutes;
  }
  if (dateType == 'yyyy/mm/dd HH:mm') {
    dateText = dateObj.getFullYear() + '/' + month + '/' + strDate + ' ' + hours + ':' + minutes;
  }
  if (dateType == 'HH:mm:ss') {
    dateText = hours + ':' + minutes + ':' + seconds;
  }
  if (dateType == 'mm:ss') {
    dateText = minutes + ':' + seconds;
  }
  if (dateType == 'HH:mm') {
    dateText = hours + ':' + minutes;
  }
  return dateText;
};

调用方法

let new data = getFormatDate(时间戳, ‘yyyy-mm-dd HH:mm:ss’)

这样就可以获得新格式的时间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值