美文网首页javascript基础入门
Javascript - Date类常用方法

Javascript - Date类常用方法

作者: 厦门_小灰灰 | 来源:发表于2019-11-19 17:43 被阅读0次

Date常用方法

构造函数 Date()

取得当天的日期,返回当前时间点的时间

//构造函数没有参数,则返回当前日期的Date对象
var date = new Date();
console.log("无参数: " + date);

//构造函数的参数为日期的毫秒数,返回距离1970年1月1日经过该毫秒后对应的日期
date = new Date(1234567);
console.log("参数为毫秒数: " + date);

//构造函数的参数为对应的日期字符串
date = new Date('2018-04-01');
console.log("参数为日期字符串: " + date);

//构造函数的参数,通过年月日,时分秒,只有年和月是必须的,其余的都有默认值
date = new Date(2019,10,25,08,12,22);
console.log("参数为年月日,时分秒: " + date);
result.png

getDate()

返回一个月中的某一天 (1 ~ 31)

getDay()

返回一周中的某一天 (0 ~ 6)。

getMonth()

返回月份 (0 ~ 11)

getFullYear()

以四位数字返回年份
getYear()已经不推荐使用了,请使用getFullYear()

getHours()

返回小时 (0 ~ 23)

getMinutes()

返回分钟 (0 ~ 59)

getSeconds()

返回秒数 (0 ~ 59)

简单示例:

var date = new Date();
console.log("getDate:" + date.getDate());
console.log("getDay:" + date.getDay());
console.log("getMonth:" + date.getMonth());
console.log("getFullYear:" + date.getFullYear());
console.log("getHours:" + date.getHours());
console.log("getMinutes:" + date.getMinutes());
console.log("getSeconds:" + date.getSeconds());

结果:


result.png

Date.parse()

可解析一个日期时间字符串,并返回 1970/1/1 午夜距离该日期时间的毫秒数

console.log(Date.parse(2018-04-01));  //1356998400000

getTime()

可返回距 1970 年 1 月 1 日之间的毫秒数,也就是所谓的时间戳,另外一种获取时间戳的方式是Date.now();

console.log(new Date().getTime());  //1574076835550
console.log(Date.now());  //1574076835553

总共会有三种方法获取时间戳:

  • Date.now()
  • dateObj.getTime()
  • +(new Date())

相关文章

网友评论

    本文标题:Javascript - Date类常用方法

    本文链接:https://www.haomeiwen.com/subject/nfnbictx.html