常用的日期时间格式化工具

总结了几个平时经常会用到的日期时间格式化方法:

1.格式化date对象,支持传入不同的格式化规则

/**
 * 格式化date对象
 * @param {Object} dateObj: 日期对象
 * @param {String} format: 格式化的规则, 默认yyyy-MM-dd HH:mm:ss
 */
function formatDate(dateObj,format="yyyy-MM-dd HH:mm:ss") {
  if (!dateObj) return "";
  let year = dateObj.getFullYear();
  let month = addZero(dateObj.getMonth() + 1);
  let day = addZero(dateObj.getDate());
  let hour = addZero(dateObj.getHours());
  let minute = addZero(dateObj.getMinutes());
  let second = addZero(dateObj.getSeconds());
  let timeFormat = "";
  // 12小时制
  if (format.indexOf("A") > 0) {
    timeFormat = hour >= 12 ? "PM" : "AM";
    hour = hour > 12 ? hour - 12 : hour;
    hour = addZero(hour);
  }
  return format
    .replace("yyyy", year)
    .replace("MM", month)
    .replace("dd", day)
    .replace("HH", hour)
    .replace("hh", hour)
    .replace("mm", minute)
    .replace("ss", second)
    .replace("A", timeFormat);
}

2.获取时间戳的方法(UTC时间戳与本地时间戳)

   获取UTC时间戳

export const UTCStamp = (date) => {
  const dateObj = date ? new Date(date) : new Date()
  const utcDateObj = new Date(
    dateObj.getUTCFullYear(),
    dateObj.getUTCMonth(),
    dateObj.getUTCDate(),
    dateObj.getUTCHours(),
    dateObj.getUTCMinutes(),
    dateObj.getUTCSeconds()
  )
  return utcDateObj.getTime()
}

    获取本地时间戳

export const localStamp = (date) =>{
  const dateObj = date ? new Date(date) : new Date()
  const utcDateObj = new Date(
    dateObj.getFullYear(),
    dateObj.getMonth(),
    dateObj.getDate(),
    dateObj.getHours(),
    dateObj.getMinutes(),
    dateObj.getSeconds()
  )
  return utcDateObj.getTime()
}

3.UTC时间转当地时间

/**
 * UTC时间转当地时间
 * @param {String} utcStr: '2018-12-05 18:03:25' 零时区
 */
export const UTCTime2LocalTime = (utcStr, format = 'yyyy-mm-dd hh:mm:ss') => {
  // ie不能解析'YYYY-MM-DD'这种格式,但所有浏览器都能兼容'YYYY/MM/DD'
  // 而后台固定返回'YYYY-MM-DD HH:mm:ss'这种格式,需要转换成'YYYY/MM/DD HH:mm:ss'
  if (!utcStr) return
  let utcDate = null
  if (typeof utcStr === 'string') utcDate = new Date(addDate(utcStr).replace(/-/g, '/'))
  else utcDate = new Date(utcStr.getTime())
  var timeOffset = utcDate.getTimezoneOffset()
  var utcTime = utcDate.getTime() - timeOffset * 60 * 1000
  utcDate.setTime(utcTime)
  return formatDate(utcDate, format)
}

4.当地时间转UTC时间

/**
 * 当地时间转UTC时间
 * @param {String} localStr: '2018-12-05 18:03:25'
 */
export const LocalTime2UTCTime = (localStr) => {
  // ie不能解析'YYYY-MM-DD'这种格式,但所有浏览器都能兼容'YYYY/MM/DD'
  // 而后台固定返回'YYYY-MM-DD HH:mm:ss'这种格式,需要转换成'YYYY/MM/DD HH:mm:ss
  if (!localStr) return
  let localDate = null
  if (typeof localStr === 'string') localDate = new Date(localStr.replace(/-/g, '/'))
  else localDate = new Date(localStr.getTime())
  var timeOffset = localDate.getTimezoneOffset()
  var localTime = localDate.getTime() + timeOffset * 60 * 1000
  localDate.setTime(localTime)
  return formatDate(localDate, 'yyyy-mm-dd hh:mm:ss')
}

5.字符串时间转时间戳 兼容IE 要用/识别

// 字符串时间 转时间戳 兼容ie 要用/识别
export const strTimeToStamp = (strTime) => {
  const date = strTime.replace(/-/g, '/')
  const timestamp = new Date(date).getTime()
  return timestamp
}

6.时间戳格式化

此处使用moment来实现格式化功能,引入moment依赖的方式可以选择通过命令 npm install moment --save 安装依赖,也可以选择将moment.js文件作为静态文件的方式引入(在项目的static文件夹下引入)

/ 时间戳格式化
export const dateFormat = (timestemp, format = 'YYYY-MM-DD HH:mm:ss') => {
  return window.moment(+new Date(timestemp)).format(format) || ''
}

7.获取当前系统时区

/**
   * 获取当前系统时区
   * @return {String} 'UTC+08:00'
   */
  getUTCTimeZone() {
    let timeOffset = new Date().getTimezoneOffset();
    let absTime = Math.abs(timeOffset);
    let symbol = timeOffset <= 0 ? "+" : "-";
    let hour = addZero(Math.floor(absTime / 60));
    let minute = addZero(Math.floor(absTime % 60));
    return `UTC${symbol}${hour}:${minute}`;
  },

8.根据日期生成年、月、日对象

  /**
 * 根据日期生成年、月、日对象
 * @param {Date} date
 * @returns {Object}
 */
 getDateObj (date){
  if (!date) return
  if (typeof date === 'string') date = new Date(date)
  if (Object.prototype.toString.call(date) !== '[object Date]') return
  return {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    hour: date.getHours(),
    min: date.getMinutes(),
    sec: date.getSeconds()
  }
},

最后是在格式化时间、日期中常用到的一个方法,个位数补零

// 个位数补零
function addZero(str) {
  return str * 1 < 10 ? `0${str * 1}` : str;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值