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]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章