时间的处理(一年、多个月、一个月、一天)
程序员文章站
2024-01-28 09:26:22
...
//时间格式化
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;
}
//获取昨天的日期
function getYestoday(date){
var yesterday_milliseconds=date.getTime()-1000*60*60*24;
var yesterday = new Date();
yesterday.setTime(yesterday_milliseconds);
var strYear = yesterday.getFullYear();
var strDay = yesterday.getDate();
var strMonth = yesterday.getMonth()+1;
if(strMonth<10)
{
strMonth="0"+strMonth;
}
datastr = strYear+"-"+strMonth+"-"+strDay;
return datastr;
}
//获得上个月在昨天这一天的日期
function getLastMonthYestdy(date){
var daysInMonth = new Array([0],[31],[28],[31],[30],[31],[30],[31],[31],[30],[31],[30],[31]);
var strYear = date.getFullYear();
var strDay = date.getDate();
var strMonth = date.getMonth()+1;
if(strYear%4 == 0 && strYear%100 != 0){
daysInMonth[2] = 29;
}
if(strMonth - 1 == 0)
{
strYear -= 1;
strMonth = 12;
}
else
{
strMonth -= 1;
}
strDay = daysInMonth[strMonth] >= strDay ? strDay : daysInMonth[strMonth];
if(strMonth<10)
{
strMonth="0"+strMonth;
}
if(strDay<10)
{
strDay="0"+strDay;
}
datastr = strYear+"-"+strMonth+"-"+strDay;
return datastr;
}
//获取当前日期前N个月的日期
function getPreMonthDay(date,monthNum)
{
var dateArr = date.split('-');
var year = dateArr[0]; //获取当前日期的年份
var month = dateArr[1]; //获取当前日期的月份
var day = dateArr[2]; //获取当前日期的日
var days = new Date(year, month, 0);
days = days.getDate(); //获取当前日期中月的天数
var year2 = year;
var month2 = parseInt(month) - monthNum;
if (month2 <=0) {
year2 = parseInt(year2) - parseInt(month2 / 12 == 0 ? 1 : parseInt(month2) / 12);
month2 = 12 - (Math.abs(month2) % 12);
}
var day2 = day;
var days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
var t2 = year2 + '-' + month2 + '-' + day2;
return t2;
}
//获得上一年在昨天这一天的日期
function getLastYearYestdy(date){
var strYear = date.getFullYear() - 1;
var strDay = date.getDate();
var strMonth = date.getMonth()+1;
if(strMonth<10)
{
strMonth="0"+strMonth;
}
if(strDay<10)
{
strDay="0"+strDay;
}
datastr = strYear+"-"+strMonth+"-"+strDay;
return datastr;
}
下一篇: 关于js的回调函数,同步回调与异步回调