前言
在前端开发中,经常会采用前后端分离模式进行开发,那么就会遇到后端传来的日期格式为时间戳格式,需要前端将时间戳转换为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 ''
}
}