Data内置对象
1.内置对象 Date 日期对象
2.创建日期对象
2.1 根据当前的系统时间来创建日期对象。
var date1 = new Date();
//a.输出日期对象的信息
console.log(date1); //Thu Dec 14 2017 20:55:24 GMT+0800
console.log(date1.toString()); //Thu Dec 14 2017 20:55:24 GMT+0800
//b.输出日期对象里面的日期部分。
console.log(date1.toDateString()); //Thu Dec 14 2017
console.log(date1.toLocaleDateString()); //2017/12/14
//c.输出日期对象里面的时间部分
console.log(date1.toTimeString()); // 20:55:24 GMT+0800 (中国标准时间)
console.log(date1.toLocaleTimeString()); // 下午8:55:24
2.2 根据指定的系统时间来创建日期对象。 参数有三种格式
//a. 给number类型的值,逗号隔开
var date2 = new Date(2000,5,6,8,20,30); //月份是从0开始的。
console.log(date2); //Tue Jun 06 2000 08:20:30 GMT+0800 (中国标准时间)
//b. 给字符串形式的年月日
var date3 = new Date("2000-5-6 8:20:30");
console.log(date3); //Sat May 06 2000 08:20:30 GMT+0800 (中国标准时间)
//c. 给毫秒的形式
var date4 = new Date(1000); //1秒=1000毫秒
console.log(date4); //给的毫秒从1970年1月1号,早八点开始算。Thu Jan 01 1970 08:00:01 GMT+0800 (中国标准时间)
2.3 获取当前的时间,毫秒形式
var date5 = Date.now();
console.log(date5); // 1513256404915
2.4 获取日期对象里面的部分内容。
// getTime() 返回毫秒数和valueOf()结果一样
// getMilliseconds()
// getSeconds() 返回0-59
// getMinutes() 返回0-59
// getHours() 返回0-23
// getDay() 返回星期几 0周日 6周6
// getDate() 返回当前月的第几天,当月的几号
// getMonth() 返回月份,从0开始
// getFullYear() 返回4位的年份 如 2016
// console.log('--------------------------------');
var date = new Date();
console.log(date.getFullYear());
console.log(date.getDate());
console.log(date.getDay());
console.log(date.getDate());
console.log(date.getMonth());
console.log(date.getFullYear());
2.5 写一个函数传过来一个日期对象,返回yyyy-MM-dd HH:mm:ss形式的字符串
其实可以用moment.js
方法一:
function getStrOfDate(date){
var year = date.getFullYear();
var month = date.getMonth()+1;
month = month < 10? "0"+month : month;
var day = date.getDate();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
return year+"-"+month+"-"+day+" "+hour+":"+min+":"+sec;
}
var date1 = new Date();
console.log(getStrOfDate(date1));// 2017-12-14 21:3:49
方法二:
function getDate(a){
return a.getFullYear()+"-"+a.getMonth()+"-"+a.getDate()+" "+a.getHours()+":"+a.getMinutes()+":"+a.getSeconds();
}
var date11 = new Date();
console.log(getDate(date11)); //2017-12-14 21:3:49
浙公网安备 33010602011771号