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

2023-05-16

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

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

创建 Date 对象的语法:

// 创建Date对象
var d = new Date()

// 返回结果: Tue Apr 30 2019
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控制台操作

// 获取当前日期
> new Date()
Tue Apr 30 2019 16:20:59 GMT+0800 (CST)

// 获取Unix时间戳的毫秒数
> new Date().getTime()
1556611808592

// 获取Unix时间戳的秒数
> new Date().getTime()/1000
1556611967.915

// 获取Unix时间戳的毫秒数,返回int型
> parseInt(new Date().getTime()/1000)
1556611987

// 获取月份 (0 ~ 11),从0开始,今天是4月30号,所以是3
> new Date().getMonth()
3
// 获取当前月份,在getMonth返回值后加1
> new Date().getMonth() + 1
4

// 获取一周中的第几天(0~6): 周日是0,从0开始,所以今天是周二,所以返回2
> new Date().getDay()
2

// 获取一个月中的某一天: 今天是4月30号,所以返回30
> new Date().getDate()
30

格式化显示时间

以下是参考代码:

var d = new Date()
var day = d.getDate()
var month = d.getMonth() + 1
var year = d.getFullYear()
var hour = d.getHours()
var minute = d.getMinutes()
var second = d.getSeconds()
var milliseconds = d.getMilliseconds()

// 输出: 2019/4/30 
document.write(year + "/" + month + "/" + day)
document.write("<br/>")

// 输出: 2019-4-30 
document.write(year + "-" + month + "-" + day) // 输出: 
document.write("<br/>")

// 输出: 2019-4-30 16:8:21.291
document.write(year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second+"."+milliseconds) 

Reference

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

[END]

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

js获取时间戳与日期格式化 的相关文章

随机推荐