欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JavaScript 时间戳格式化技巧

最编程 2024-08-03 20:42:29
...

js时间戳格式化方法

方法一

function formatTime(value) {
	if(value) {
		let date = new Date(value * 1000)	// 时间戳为秒:10位数
		//let date = new Date(value)	// 时间戳为毫秒:13位数
		let year = date.getFullYear()
		let month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
		let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
		let hour = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
		let minute = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
		let second = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
		return `${year}-${month}-${day} ${hour}:${minute}:${second}`
	} else {
		return ''
	}
}

console.log(formatTime(1575277007))	

方法二

// 时间戳转xxxx-xx-xx格式的日期
export const timestampToDate = (timestamp, type = false) => {
  const fullTime = new Date(timestamp)
  const year = fullTime.getFullYear()
  const month = (fullTime.getMonth() + 1) < 10 ? '0' + (fullTime.getMonth() + 1) : (fullTime.getMonth() + 1)
  const day = (fullTime.getDate()) < 10 ? '0' + (fullTime.getDate()) : (fullTime.getDate())
  const hours = (fullTime.getHours()) < 10 ? '0' + (fullTime.getHours()) : (fullTime.getHours())
  const minutes = (fullTime.getMinutes()) < 10 ? '0' + (fullTime.getMinutes()) : (fullTime.getMinutes())
  const seconds = (fullTime.getSeconds()) < 10 ? '0' + (fullTime.getSeconds()) : (fullTime.getSeconds())
  return type === false ? `${year}-${month}-${day}` : `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

mysql中 时间戳生成方法

select unix_timestamp(now())
unix_timestamp(now())
1575277371

js 生成时间戳


> Date.parse(new Date().toString())
< 1575277771000
# 13位,但是末尾3位位000,可截取前10位
> Date.parse(new Date())/1000
< 1575278320

> (new Date()).valueOf()
< 1575277823412

> new Date().getTime()
< 1575277839379

> Math.round(new Date().getTime()/1000)
< 1575277858