整理了一下Date下的一些方法和实例,方便大家一起复习。
1.下例展示了用来创建一个日期对象的多种方法。
var today = new Date();
var today = new Date(1453094034000);// by timestamp(accurate to the millimeter)
var birthday = new Date("December 17, 1995 03:24:00");
var birthday = new Date("1995-12-17T03:24:00");
var birthday = new Date(1995,11,17);
var birthday = new Date(1995,11,17,3,24,0);
2.两位数年份表示 1900 - 1999 年
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
// 弃用的方法, 98在这里被映射为1998
date.setYear(98); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
date.setFullYear(98); // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
3.计算经过的时间
// 使用 Date 对象
var start = Date.now();
// 这里进行耗时的方法调用:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // 运行时间的毫秒值
// 使用内建的创建方法
var start = new Date();
// 这里进行耗时的方法调用:
doSomethingForALongTime();
var end = new Date();
var elapsed = end.getTime() - start.getTime(); // 运行时间的毫秒值
// to test a function and get back its return
function printElapsedTime (fTest) {
var nStartTime = Date.now(),
vReturn = fTest(),
nEndTime = Date.now();
alert("Elapsed time: " + String(nEndTime - nStartTime) + " milliseconds");
return vReturn;
}
yourFunctionReturn = printElapsedTime(yourFunction);
4.Date.prototype 方法
Date.prototype.getDate()
根据本地时间,返回一个指定的日期对象为一个月中的第几天。
var birthday = new Date('August 19, 1975 23:15:30');
var date1 = birthday.getDate();
console.log(date1);
// expected output: 19
Date.prototype.getDay()
方法根据本地时间,返回一个具体日期中一周的第几天,0 表示星期天。
var birthday = new Date('August 19, 1975 23:15:30');
var day1 = birthday.getDay();
// Sunday - Saturday : 0 - 6
console.log(day1);
// expected output: 2
Date.prototype.getFullYear()
方法根据本地时间返回指定日期的年份。
var moonLanding = new Date('July 20, 69 00:20:18');
console.log(moonLanding.getFullYear());
// expected output: 1969
Date.prototype.getHours()
方法根据本地时间,返回一个指定的日期对象的小时。
var birthday = new Date('March 13, 08 04:20');
console.log(birthday.getHours());
// expected output: 4
Date.prototype.getMilliseconds()
方法,根据本地时间,返回一个指定的日期对象的毫秒数。
var moonLanding = new Date('July 20, 69 00:20:18');
moonLanding.setMilliseconds(123);
console.log(moonLanding.getMilliseconds());
// expected output: 123
Date.prototype.getMinutes()
方法根据本地时间,返回一个指定的日期对象的分钟数。
var birthday = new Date('March 13, 08 04:20');
console.log(birthday.getMinutes());
// expected output: 20
Date.prototype.getMonth()
根据本地时间,返回一个指定的日期对象的月份,为基于0的值(0表示一年中的第一月)。
var moonLanding = new Date('July 20, 69 00:20:18');
console.log(moonLanding.getMonth()); // (January gives 0)
// expected output: 6
Date.prototype.getSeconds()
方法根据本地时间,返回一个指定的日期对象的秒数。
var moonLanding = new Date('July 20, 69 00:20:18');
console.log(moonLanding.getSeconds());
// expected output: 18
Date.prototype.getTime()
方法返回一个时间的格林威治时间数值。
var moonLanding = new Date('July 20, 69 00:20:18 GMT+00:00');
// milliseconds since Jan 1, 1970, 00:00:00.000 GMT
console.log(moonLanding.getTime());
// expected output: -14254782000
总结了一下关于Date的一些常用方法操作以及实例,欢迎大家多多吐槽留言,我是小强,我们下次见面。