Math對象
定義: math對象是一個靜態對象(不需要實例化,可以直接用)
Math對象常用的方法:
1. min() 和 max() :取最小值和最大值
let max = Math.max(3,5,8,1);
let min = Math.min(3,5,8,1);
console.log(max); // 8
console.log(min); // 1
2.舍入方法ceil()、floor() 和round()
ceil() 方法執行向上舍入, floor() 方法執行向下舍入,round() 方法執行四捨五入。
let num = 3.14;
console.log(Math.ceil(num)); // 4
console.log(Math.floor(num)); // 3
console.log(Math.round(num)); // 3
Date對象
時間戳:從1970年到現在的秒數
常用方法:
1.獲取到現在的毫秒數:
let now = Date.now();
console.log(now); // 1511767644238
let date = new Date();
date .getYear(); //獲取當前年份(2位)
date .getFullYear(); //獲取完整的年份(4位)
date .getMonth(); //獲取當前月份(0-11,0代表1月)
date .getDate(); //獲取當前日(1-31)
date .getDay(); //獲取當前星期X(0-6,0代表星期天)
date .getTime(); //獲取當前時間(從1970.1.1開始的毫秒數)
date .getHours(); //獲取當前小時數(0-23)
date .getMinutes(); //獲取當前分鐘數(0-59)
date .getSeconds(); //獲取當前秒數(0-59)
date .getMilliseconds(); //獲取當前毫秒數(0-999)
date .toLocaleDateString(); //獲取當前日期
var mytime=date .toLocaleTimeString(); //獲取當前時間
date .toLocaleString( ); //獲取日期與時間
2.獲得當前時間
//獲取當前時間
function getNowFormatDate() {
let date = new Date();
//分隔符
let seperator1 = "-";
let seperator2 = ":";
//獲取當前月份
let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
//獲得當前的日
let strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
//獲取時、分、秒
let hour = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + seperator2 + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + seperator2 + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
//將日期拼接
let currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + hour;
return currentdate;
}
let nowDate = getNowFormatDate();
console.log(nowDate);