【新】js 时间戳转日期格式(自定义日期格式)

前言

在前端开发中,经常会采用前后端分离模式进行开发,那么就会遇到后端传来的日期格式为时间戳格式,需要前端将时间戳转换为UI设计图所设计的日期格式,本文分享了一个自定义方法将时间戳转换为日期格式

以下方法可以自定义所需要的日期格式(以2021年9月1日 12:30:30为例):

  • Y-m-d h:i:s转换为2021-09-01 12:30:30
  • m-d h:i:s转换为09-01 12:30:30
  • m-d h:i转换为09-01 12:30
  • Y年m月d日h时i分s秒转换为2021年09月01日12时30分30秒
  • ====
/**
 * 日期格式转换 Y-m-d h:i:s
 * @param {String} time
 * @param {String} format
 */
export function timeStamp2String(time, format) {
  const dateTime = new Date()
  dateTime.setTime(time * 1000)
  const year = dateTime.getFullYear()
  const month = dateTime.getMonth() + 1 < 10 ? '0' + (dateTime.getMonth() + 1) :     dateTime.getMonth() + 1
  const date = dateTime.getDate() < 10 ? '0' + dateTime.getDate() : dateTime.getDate()
  const hour = dateTime.getHours() < 10 ? '0' + dateTime.getHours() : dateTime.getHours()
  const minute = dateTime.getMinutes() < 10 ? '0' + dateTime.getMinutes() : dateTime.getMinutes()
  const second = dateTime.getSeconds() < 10 ? '0' + dateTime.getSeconds() : dateTime.getSeconds()
  // 返回字符串格式
  let dateInfo = ''
  const yIndex = format.search('Y')
  const mIndex = format.search('m')
  const dIndex = format.search('d')
  const hIndex = format.search('h')
  const iIndex = format.search('i')
  const sIndex = format.search('s')
  dateInfo += `${str(year, yIndex)}`
  dateInfo += `${str(month, mIndex)}`
  dateInfo += `${str(date, dIndex)}`
  dateInfo += `${str(hour, hIndex)}`
  dateInfo += `${str(minute, iIndex)}`
  dateInfo += `${str(second, sIndex)}`
  return dateInfo
  function str(number, index) {
    if (index > -1) return `${number}${format.slice(index + 1, index + 2)}`
    else return ''
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值