使用生成一个新的包含当前日期和时间对象。new Date()Date
请注意, Date() 不带参数的调用等效于 。new Date(Date.now())
一旦有了日期对象,就可以应用几种可用方法中的任何一种来提取其属性(例如getFullYear(),获取4位数字的年份)。
以下是一些常见的日期方法。
var year = (new Date()).getFullYear(); console.log(year); // 样本输出:2016年
var month = (new Date()).getMonth(); console.log(month); // 样本输出:0
请注意,0 =一月。这是因为月份的范围是0到11,因此通常希望将其添加+1到索引中。
var day = (new Date()).getDate(); console.log(day); // 样本输出:31
var hours = (new Date()).getHours(); console.log(hours); // 样本输出:10
var minutes = (new Date()).getMinutes(); console.log(minutes); // 样本输出:39
var seconds = (new Date()).getSeconds(); console.log(second); // 样本输出:48
要获取Date对象实例的毫秒数(范围从0到999),请使用其getMilliseconds方法。
var milliseconds = (new Date()).getMilliseconds(); console.log(milliseconds); // 输出:毫秒
var now = new Date(); // 将日期转换为UTC时区格式的字符串: console.log(now.toUTCString()); // 输出:2017年6月21日星期三09:13:01 GMT
静态方法返回自1970年1月1日UTC以来经过的毫秒数。要使用该对象的实例获取自该时间以来经过的毫秒数,请使用其方法。Date.now()DategetTime
// 立即使用Date的静态方法获取毫秒 console.log(Date.now()); // 使用Date实例的getTime方法获取毫秒数 console.log((new Date()).getTime());