1、创建当前日期:var date = new Date()
2、创建指定日期:var date = new Date("2018-07-23")
3、js提供的日期操作方法:
getYear(); //获取当前年份(2位)
getFullYear(); //获取完整的年份(4位,1970-????)
getMonth(); //获取当前月份(0-11,0代表1月)
getDate(); //获取当前日(1-31)
getDay(); //获取当前星期X(0-6,0代表星期天)
getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
getHours(); //获取当前小时数(0-23)
getMinutes(); //获取当前分钟数(0-59)
getSeconds(); //获取当前秒数(0-59)
getMilliseconds(); //获取当前毫秒数(0-999)
toLocaleDateString(); //获取当前日期
var mytime=toLocaleTimeString(); //获取当前时间
toLocaleString( ); //获取日期与时间
4、日期格式化:
function formatDate(time, format = 'YY-MM-DD hh:mm:ss') {
var date = new Date(time);
var year = date.getFullYear(),
month = date.getMonth() + 1,//月份是从0开始的
day = date.getDate(),
hour = date.getHours(),
min = date.getMinutes(),
sec = date.getSeconds();
var preArr = Array.apply(null, Array(10)).map(function (elem, index) {
return '0' + index;
});////开个长度为10的数组 格式为 00 01 02 03
var newTime = format.replace(/YY/g, year)
.replace(/MM/g, preArr[month] || month)
.replace(/DD/g, preArr[day] || day)
.replace(/hh/g, preArr[hour] || hour)
.replace(/mm/g, preArr[min] || min)
.replace(/ss/g, preArr[sec] || sec);
return newTime;
}
console.log(formatDate(new Date().getTime()));//2017-05-12 10:05:44
console.log(formatDate(new Date().getTime()), 'YY年MM月DD日');//2017年05月12日
console.log(formatDate(new Date().getTime()), '今天是YY/MM/DD hh:mm:ss');//今天是2017/05/12 10:07:45
5、日期间隔
// 算两个两个日期间隔
start = new Date("2018-07-22");
end = new Date("2018-07-25");
// 两个日期相减是毫秒数
console.log(end - start) // 259200000
// 间隔天数
console.log((end - start) / 86400000)
// 间隔小时,分钟依此类推
6、浏览器中的时间细节问题
上述实在谷歌控制台执行的命令,可以看到
new Date()创建的是当前时间
new Date("2017-07-23") 创建的是当天的8点的时间,这边特别要注意。
new Date("2017-07-23 00:00:00:0")创建的是当天0的0分0秒0毫秒的时间,真正的一天的开始。