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

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]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Web后端技术

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值