javascript 时间戳正逆向格式化

一、将时间戳格式化为标准时间

代码

function convert (obj, def) {
  if (!obj) {
    return def
  }

  if (obj instanceof Date) {
    return obj
  }

  if (/^[-+]?[0-9]+$/.test(obj)) {
    obj = parseInt(obj)
  } else {
    obj = obj.replace(/-/g, '/')
  }

  if (/^\d?\d:\d?\d/.test(obj)) {
    obj = getDate(new Date()) + ' ' + obj
  }

  obj = new Date(obj)
  // Invalid Date
  if (isNaN(obj.getTime())) {
    obj = def
  }
  return obj
}

使用

const date = 1362240000000  //时间搓
console.log('convert',convert(date))
// 返回 Sun Mar 03 2013 00:00:00 GMT+0800 (CST)

二、将常用时间格式转换为标准时间(2012-01-04, 2012年-2月-12日)

代码

  function parse(str) {
    if (!str || typeof str !== 'string') {
      return str;
    }

    const [datePart, timePart = '00:00:00'] = str.split(/\s+/);
    const [year, month = 1, day = 1] = datePart.split(/\D+/);
    if (!year) {
      return null;
    }

    const [hours = 0, minutes = 0, seconds = 0] = timePart.split(/\D+/);
    const result = new Date(year, month - 1, day, hours, minutes, seconds);
    return isNaN(+result) ? null : result;
  }

使用

const str= "2013-03-3日";
console.log(parse(str))
// 返回  Sun Mar 03 2013 00:00:00 GMT+0800 (CST)

三、将时间戳格式化为固定格式的通用时间(2012-03-23或者其他格式)

代码

说明: 此方法依赖convert将时间戳格式化为标准时间

export function format (date, fmt = 'yyyy-MM-dd') {
  if (!date) { return '' }
  if (!(date instanceof Date)) {
    date = convert(date)
  }

  if (isNaN(date.getTime())) {
    return 'Invalid Date'
  }

  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

使用

const date=1362240000000
console.log(format(date, 'yyyy年MM月dd日'))
// 2013年03月03日
console.log(format(date, 'yyyy/MM/dd日'))
// 2013/03/03
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容