Date时间对象相关方法及时间戳与日期格式的转换汇总

经常涉及到时间的转换总是会忘记这些方法,做个笔记方便备查。

一、整体时间

获取最新整体时间: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
}

目前暂时就是这些,有新的内容会相继加入。
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值