日期基本数据:
var myDate = new Date(); //Date 对象会自动把当前日期和时间保存为其初始值
myDate.getYear(); //返回当前年份(2位);请使用 getFullYear() 方法代替
myDate.getFullYear(); //返回完整的年份(4位,1970-????)
myDate.getMonth(); //返回当前月份(0-11,0表示1月)
myDate.getDate(); //返回当前日(1-31)
myDate.getDay(); //返回当前星期名(0-6,0表示星期天)
myDate.getHours(); //返回当前小时数(0-23)
myDate.getMinutes(); //返回当前分钟数(0-59)
myDate.getSeconds(); //返回当前秒数(0-59)
myDate.getMilliseconds(); //返回当前毫秒数(0-999)
myDate.getTime(); //返回1970年1月1日至今的毫秒数
myDate.toLocaleString(); //根据本地时间格式,把 Date 对象转换为字符串
myDate.toLocaleTimeString(); //根据本地时间格式,把 Date 对象的时间部分转换为字符串
myDate.toLocaleDateString(); //根据本地时间格式,把 Date 对象的日期部分转换为字符串
var nowDateFormat = myDate.getFullYear() + '-' + (myDate.getMonth() + 1) + '-' + myDate.getDate();// result:2021-2-20
//您可以使用名称数组,并使用 getMonth() 将月份作为名称返回:
var months = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var nowMonth = months[myDate.getMonth()]; //result:"February"
//您可以使用名称数组,并使用 getDay() 将星期名作为名称返回:
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var nowWeekDay = days[myDate.getDay()]; //result:"Saturday"
日期相关算法:
var nowDate = new Date();
var latestYear = nowDate.getFullYear();//当前年份
var latestMonth = nowDate.getMonth() + 1;//当前月份
var latestDay = new Date().getDate();//当前号数//当前月总天数、当前月末尾号数
var latestMonthDay = new Date(latestYear, latestMonth, 0).getDate();
//上月总天数、上月末尾号数
var preMonthDay = new Date(latestYear, (latestMonth - 1), 0).getDate();
//今天
var today= latestYear + '-' + latestMonth + '-' + latestDay;
//今年年初
var currentYearStart = latestYear + '-01-01';
//本月初
var currentMonthStart = latestYear + '-' + latestMonth + '-01';
//本月末
var currentMonthEnd = latestYear + '-' + latestMonth + '-' + latestMonthDay;
//上月初
var preMonthStart = latestYear + '-' + (latestMonth - 1) + '-01';
//上月末
var preMonthEnd = latestYear + '-' + (latestMonth - 1) + '-' + preMonthDay;