js获取时间戳与日期格式化

╰半橙微兮° 2022-04-25 02:36 551阅读 0赞

js获取时间戳与日期格式化

Date 对象用于处理日期和时间。

创建 Date 对象的语法:

  1. // 创建Date对象
  2. var d = new Date()
  3. // 返回结果: Tue Apr 30 2019
  4. new Date().toDateString()

Date对象常用方法:

  • getFullYear(): 从 Date 对象以四位数字返回年份.
  • getDate(): 从 Date 对象返回一个月中的某一天 (1 ~ 31).
  • getMonth(): 从 Date 对象返回月份 (0 ~ 11).
  • getHours(): 返回 Date 对象的小时 (0 ~ 23).
  • getMinutes(): 返回 Date 对象的分钟 (0 ~ 59).
  • getSeconds(): 返回 Date 对象的秒数 (0 ~ 59).
  • getMilliseconds(): 返回 Date 对象的毫秒(0 ~ 999).
  • getDay(): 从 Date 对象返回一周中的某一天 (0 ~ 6)。

在Chrome浏览器console控制台操作

  1. // 获取当前日期
  2. > new Date()
  3. Tue Apr 30 2019 16:20:59 GMT+0800 (CST)
  4. // 获取Unix时间戳的毫秒数
  5. > new Date().getTime()
  6. 1556611808592
  7. // 获取Unix时间戳的秒数
  8. > new Date().getTime()/1000
  9. 1556611967.915
  10. // 获取Unix时间戳的毫秒数,返回int型
  11. > parseInt(new Date().getTime()/1000)
  12. 1556611987
  13. // 获取月份 (0 ~ 11),从0开始,今天是4月30号,所以是3
  14. > new Date().getMonth()
  15. 3
  16. // 获取当前月份,在getMonth返回值后加1
  17. > new Date().getMonth() + 1
  18. 4
  19. // 获取一周中的第几天(0~6): 周日是0,从0开始,所以今天是周二,所以返回2
  20. > new Date().getDay()
  21. 2
  22. // 获取一个月中的某一天: 今天是4月30号,所以返回30
  23. > new Date().getDate()
  24. 30

格式化显示时间

以下是参考代码:

  1. var d = new Date()
  2. var day = d.getDate()
  3. var month = d.getMonth() + 1
  4. var year = d.getFullYear()
  5. var hour = d.getHours()
  6. var minute = d.getMinutes()
  7. var second = d.getSeconds()
  8. var milliseconds = d.getMilliseconds()
  9. // 输出: 2019/4/30
  10. document.write(year + "/" + month + "/" + day)
  11. document.write("<br/>")
  12. // 输出: 2019-4-30
  13. document.write(year + "-" + month + "-" + day) // 输出:
  14. document.write("<br/>")
  15. // 输出: 2019-4-30 16:8:21.291
  16. document.write(year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second+"."+milliseconds)

Reference

http://www.w3school.com.cn/jsref/jsref_obj_date.asp

[END]

发表评论

表情:
评论列表 (有 0 条评论,551人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JS获取时间

    此文章来自转载 : 链接: [JS获取本周、本季度、本月、上月、本年的开始日期、结束日期][JS]. / 获取本周、本季度、本月、上月的开始日期、结束日期 /