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:274、倒计时函数
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; } }
