1、js創建時間對象
new Date(“month dd,yyyy hh:mm:ss”);
new Date(“month dd,yyyy”);
new Date(yyyy,mth,dd,hh,mm,ss);
new Date(yyyy,mth,dd);
new Date(ms);
var date1 = new Date('10 10,2010 10:10:10');
var date2 = new Date('10 10,2010');
var date3 = new Date(2010,10,10,10,10,10);
var date4 = new Date(2010,10,10);
var date5 = new Date(1539670798651);
2、Date對象的相關方法
var date = new Date();
date.getFullYear(); //返回當前時間的年份
date.getMonth(); //返回當前時間的月份(0-11)
date.getDate(); //返回當前月的當前天
date.getHours(); //返回當前的小時數
date.getMinutes(); //返回當前分鐘數
date.getSeconds(); //返回當前月的秒數
date.getTime(); //返回時間戳 (1970 年 1 月 1 日至今的毫秒數)
date.getDay(); //返回當前周的當前天
/* 上面的函數比較常用,還有相對有set方法 */
date.toString();
date.toLocaleString();
date.toLocaleDateString();
date.toLocaleTimeString();
date.toTimeString();
date.toDateString();
3、時間對象轉換爲我們的平常時間
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"H+": this.getHours(), //小時
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
var now = new Date();
console.log(now.Format('YYYY-MM-dd HH:mm:ss')); //2018-10-16 15:14:27
4、倒計時函數
Date.prototype.countDown = function(){
if(arguments.length == 1 && !isNaN(arguments[0])){
var arg1 = arguments[0], result = {} ,status = 1;
var oldarg1length = arg1.toString().length;
if(oldarg1length < 13){
for(var i = 0; i < 13 - oldarg1length; i++){
arg1 += '0';
}
}
if(oldarg1length > 13)
arg1 = arg1.toString().substring(0,13);
var now = new Date();
var point_now = new Date(Number(arg1));
if(point_now.getTime() > now.getTime()){
var totalSecs = result.totalSecs = (point_now - now)/1000;
var days = result.days = Math.floor(totalSecs/3600/24);
var hours = result.hours = Math.floor((totalSecs-days*24*3600)/3600);
var mins = result.mins = Math.floor((totalSecs-days*24*3600-hours*3600)/60);
var secs = result.secs = Math.floor((totalSecs-days*24*3600-hours*3600-mins*60));
result.status = status;
}else result.status = 0;
return result;
}
}