经常涉及到时间的转换总是会忘记这些方法,做个笔记方便备查。
一、整体时间
获取最新整体时间:new Date()
设置整体时间:new Date('年-月-日 时:分:秒')
二、年
获取年:getFullYear() // 返回当前年份
设置年:setFullYear('年') // 返回时间戳
三、月(获取到的月份需要+1)
获取月:getMonth() // 返回当前月份
设置月:setMonth('月') // 返回时间戳
四、日
获取日:getDate() // 返回当前日
设置日:setDate('日') // 返回时间戳
五、星期的第几天
获取星期的第几天:getDate() // 返回当前是星期几
六、小时
获取小时:getHours() // 返回当前的小时
设置小时:setHours('时') // 返回时间戳
七、分钟
获取分钟:getMinutes() // 返回当前的分钟
设置分钟:setMinutes('分') // 返回时间戳
八、秒
获取秒:getSeconds() // 返回当前的秒
设置秒:setSeconds('秒') // 返回时间戳
九、时间戳
获取时间戳:getTime() // 返回时间戳
十、时间戳转日期格式
/**
* @param {number} timestamp 时间戳
* @returns {string}
*/
function timestampToTime(timestamp) {
if (timestamp === 0 || timestamp == null) {
return ''
} else {
var date = new Date(timestamp * 1000) //时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear() + '-'
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
var D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
var H = date.getHours() + ':'
var M2 = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
var S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return Y + M + D + H + M2 + S
}
}
十一、获取N天前或后的日期
/**
* 获取N天的时间
* @param {number} n 天数 N天前或N天后
* @param {string} nowDate 当前时间
* @returns {string}
*/
function getNDateTime(n, nowDate = '') {
var currentDate = new Date()
if (nowDate) {
currentDate = new Date(nowDate)
}
var preDate = new Date(currentDate.getTime() + n * 24 * 3600 * 1000)
const year = preDate.getFullYear()
var month = ('0' + (preDate.getMonth() + 1)).slice(-2)
var sdate = ('0' + preDate.getDate()).slice(-2)
const s = year + '-' + month + '-' + sdate
return s
}
目前暂时就是这些,有新的内容会相继加入。