javascript一些有关date操作的方法

<span style="font-size:12px;">    // 判断日期是不是周末
    function checkWeekend() {
        var startDate = $("input[name=begin_time]").val();
        var endDate = $("input[name=end_time]").val();
        var weekDays = 0;// 开始日期和结束日期之间相隔的周末天数
        var count = 0;// 循环次数
        if(startDate <= endDate) {// 开始日期必须小于结束日期,防止死循环
            var nextDate = startDate;
            while(nextDate != endDate) {
                nextDate = getNextDate(nextDate,1);
                
                // 判断nextDate是否是周末,如果是周末则减去
                var day = new Date(nextDate).getDay();//0-周日,6-周六
                if(day==0 || day==6) {
                    weekDays ++;
                }
                
                count ++;
                if(count>=180) {// 防止死循环
                    break;
                }
            }
        }
        
        var day = $("input[name=day]").val();
        $("input[name=day]").val(day-weekDays);// 减去周末时间
    }</span>


<span style="font-size:12px;">        // 字符转日期
        getDate : function(strDate) {    
            var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/,    
             function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');    
            return date;    
        },
        // 取得下一个工作日
        getNextWorkDay: function(dateStr){
        	var _this = this;
        	function getNextDay(d){
                d = new Date(d);
                d = +d + 1000*60*60*24;
                d = new Date(d);
                //return d;
                //格式化
                var year = d.getFullYear();
                var month = d.getMonth()+1;
                month = month < 10?'0'+month:month;
                var date = d.getDate() < 10?'0'+d.getDate():d.getDate();
                return year+"-"+month+"-"+date;
            }
        	var nextDay = getNextDay(dateStr);
        	if(!_this.checkWeekDay(nextDay)){
        		nextDay = _this.getNextWorkDay(nextDay);
        	}
        	return nextDay;
        },
        // 判断是否周末
        checkWeekDay: function(dateStr){
        	var d = this.getDate(dateStr);
        	if(d.getDay() == 6 || d.getDay() == 0){
        		return false;
        	}else{
        		return true;
        	}
        },
        // 取得两天之间的工作日(除周末)
        getWorkDay: function(mode, beginDay, endDay) {
        	
        	var d1 = this.getDate(beginDay);
            var d2 = this.getDate(endDay);
            
            var dateS = this.getDate(beginDay)
            var dateE = this.getDate(endDay);
            
            var day = (dateE.getTime() - dateS.getTime()) / (1000 * 60 * 60 * 24);
            
            var w1 = dateS.getDay();
            var w2 = dateE.getDay();
            
            var w = parseInt(day / 7) * 2;
            w += w1 > w2 ? 2 : w1 == 0 ? 1 : 0;
            
           	return day - w + 1;
//            //计算工作日
//            var Holiday = ["2015-07-13", "2015-07-14", "2015-07-15", "2012-01-22", "2012-01-23", "2012-01-24", "2012-01-25", "2012-01-26", "2012-01-27", "2012-01-28", "2012-04-02", "2012-04-03", "2012-04-04", "2012-04-29", "2012-04-30", "2012-05-01", "2012-06-22", "2012-06-23", "2012-06-24", "2012-09-30", "2012-10-01", "2012-10-02", "2012-10-03", "2012-10-04", "2012-10-05", "2012-10-06", "2012-10-07"];
//            var WeekendsOff = ["2015-07-11", "2012-01-21", "2012-01-29", "2012-03-31", "2012-04-01", "2012-04-28", "2012-09-29"];
//
//            function nearlyWeeks(mode, weekcount, end) {
//                if (mode == undefined) {
//                    mode = "cn"
//                }
//                if (weekcount == undefined) {
//                    weekcount = 0
//                }
//                if (end != undefined) {
//                    end = new Date(new Date(end).toDateString())
//                } else {
//                    end = new Date(new Date().toDateString())
//                }
//                var days = 0;
//                if (mode == "cn") {
//                    days = (end.getDay() == 0 ? 7 : end.getDay()) - 1
//                } else {
//                    days = end.getDay()
//                }
//                return new Date(end.getTime() - (days + weekcount * 7) * 24 * 60 * 60 * 1000)
//            }
//
//            function getWorkDayCount(mode, beginDay, endDay) {
//                var begin = new Date(beginDay.toDateString());
//                var end = new Date(endDay.toDateString());
//                var daytime = 24 * 60 * 60 * 1000;
//                var days = (end - begin) / daytime + 1;
//                var beginWeekFirstDay = nearlyWeeks(mode, 0, beginDay.getTime()).getTime();
//                var endWeekOverDay = nearlyWeeks(mode, 0, endDay.getTime()).getTime() + 6 * daytime;
//                var weekEndCount = ((endWeekOverDay - beginWeekFirstDay) / daytime + 1) / 7 * 2;
//                if (mode == "cn") {
//                    if (endDay.getDay() > 0 && endDay.getDay() < 6) {
//                        weekEndCount -= 2
//                    } else {
//                        if (endDay.getDay() == 6) {
//                            weekEndCount -= 1
//                        }
//                    }
//                    if (beginDay.getDay() == 0) {
//                        weekEndCount -= 1
//                    }
//                } else {
//                    if (endDay.getDay() < 6) {
//                        weekEndCount -= 1
//                    }
//                    if (beginDay.getDay() > 0) {
//                        weekEndCount -= 1
//                    }
//                }
//                $.each(WeekendsOff, function(i, offitem) {
//                    var itemDay = new Date(offitem.split("-")[0] + "/" + offitem.split("-")[1] + "/" + offitem.split("-")[2]);
//                    if (itemDay.getTime() >= begin.getTime() && itemDay.getTime() <= end.getTime() && (itemDay.getDay() == 0 || itemDay.getDay() == 6)) {
//                        weekEndCount -= 1
//                    }
//                });
//                $.each(Holiday, function(i, itemHoliday) {
//                    var itemDay = new Date(itemHoliday.split("-")[0] + "/" + itemHoliday.split("-")[1] + "/" + itemHoliday.split("-")[2]);
//                    if (itemDay.getTime() >= begin.getTime() && itemDay.getTime() <= end.getTime() && itemDay.getDay() > 0 && itemDay.getDay() < 6) {
//                        weekEndCount += 1
//                    }
//                });
//                return days - weekEndCount
//            }
//
//            function getDate(strDate) {
//                var date = eval("new Date(" + strDate.replace(/\d+(?=-[^-]+$)/, function(a) {
//                    return parseInt(a, 10) - 1
//                }).match(/\d+/g) + ")");
//                return date
//            }
//            var r = getWorkDayCount("cn", getDate(beginDay), getDate(endDay));
//            return r == undefined ? 0 : r;
        }</span>

// 获取日期:昨天今天和明天、后天

<span style="font-size:12px;"><body> 
<script language="JavaScript" type="text/javascript"> 
function GetDateStr(AddDayCount) { 
    var dd = new Date(); 
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期 
    var y = dd.getFullYear(); 
    var m = dd.getMonth()+1;//获取当前月份的日期 
    var d = dd.getDate(); 
    return y+"-"+m+"-"+d; 
} 
document.write("前天:"+GetDateStr(-2)); 
document.write("<br />昨天:"+GetDateStr(-1)); 
document.write("<br />今天:"+GetDateStr(0)); 
document.write("<br />明天:"+GetDateStr(1)); 
document.write("<br />后天:"+GetDateStr(2)); 
document.write("<br />大后天:"+GetDateStr(3)); 
</script> 

</body> </span>
其中有一种方法是:Date.parse(dateVal),此函数功能强大,但是有个致命的缺点,那就是不支持我们常用的“年-月-日”格式,短日期可以使用“/”或“-”作为日期分隔符,但是必须用月/日/年的格式来表示,例如"7/20/96"。 


另一种方法是使用 split,比如: 

var dtStr = "2006-11-25"; 
var dtArr = dtStr.split("-"); 
var dt = new Date(dtArr[0], dtArr[1], dtArr[2]); 

但这种方法较为死板,要求固定的日期格式,只有在没有办法的情况下才用。 

如果我们可以将年月日拆分开,就尽量将其拆开,比如 ASP 分别输出年月日。然后用 new Date 来处理,返回的便是日期类型。 

日期格式化 

<script language="javascript" type="text/javascript"><!-- 
/** 
* 对Date的扩展,将 Date 转化为指定格式的String 
* 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符 
* 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
* eg: 
* (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
* (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04 
* (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04 
* (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04 
* (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18 
*/ 
Date.prototype.pattern=function(fmt) { 
var o = { 
"M+" : this.getMonth()+1, //月份 
"d+" : this.getDate(), //日 
"h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时 
"H+" : this.getHours(), //小时 
"m+" : this.getMinutes(), //分 
"s+" : this.getSeconds(), //秒 
"q+" : Math.floor((this.getMonth()+3)/3), //季度 
"S" : this.getMilliseconds() //毫秒 
}; 
var week = { 
"0" : "\u65e5", 
"1" : "\u4e00", 
"2" : "\u4e8c", 
"3" : "\u4e09", 
"4" : "\u56db", 
"5" : "\u4e94", 
"6" : "\u516d" 
}; 
if(/(y+)/.test(fmt)){ 
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
} 
if(/(E+)/.test(fmt)){ 
fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]); 
} 
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; 
} 

var date = new Date(); 
window.alert(date.pattern("yyyy-MM-dd hh:mm:ss")); 
// --></script> 
<span style="font-size:12px;">
</span>
<span style="font-size:12px;">// js获取当前日期、前一天、后一天的日期的例子
</span>
<span style="font-size:12px;">< script >
function addByTransDate(dateParameter, num) {
	var translateDate = "",
		dateString = "",
		monthString = "",
		dayString = "";
	translateDate = dateParameter.replace("-", "/").replace("-", "/");
	var newDate = new Date(translateDate);
	newDate = newDate.valueOf();
	newDate = newDate + num * 24 * 60 * 60 * 1000;
	newDate = new Date(newDate);
	//如果月份长度少于2,则前加 0 补位
	if ((newDate.getMonth() + 1).toString().length == 1) {
		monthString = 0 + "" + (newDate.getMonth() + 1).toString();
	} else {
		monthString = (newDate.getMonth() + 1).toString();
	}
	//如果天数长度少于2,则前加 0 补位
	if (newDate.getDate().toString().length == 1) {
		dayString = 0 + "" + newDate.getDate().toString();
	} else {
		dayString = newDate.getDate().toString();
	}
	dateString = newDate.getFullYear() + "-" + monthString + "-" + dayString;
	return dateString;
}

function reduceByTransDate(dateParameter, num) {
	var translateDate = "",
		dateString = "",
		monthString = "",
		dayString = "";
	translateDate = dateParameter.replace("-", "/").replace("-", "/");
	var newDate = new Date(translateDate);
	newDate = newDate.valueOf();
	newDate = newDate - num * 24 * 60 * 60 * 1000;
	newDate = new Date(newDate);
	//如果月份长度少于2,则前加 0 补位
	if ((newDate.getMonth() + 1).toString().length == 1) {
		monthString = 0 + "" + (newDate.getMonth() + 1).toString();
	} else {
		monthString = (newDate.getMonth() + 1).toString();
	}
	//如果天数长度少于2,则前加 0 补位
	if (newDate.getDate().toString().length == 1) {
		dayString = 0 + "" + newDate.getDate().toString();
	} else {
		dayString = newDate.getDate().toString();
	}
	dateString = newDate.getFullYear() + "-" + monthString + "-" + dayString;
	return dateString;
}
//得到日期 主方法

function showTime(pdVal) {
	var trans_day = "";
	var cur_date = new Date();
	var cur_year = new Date().format("yyyy");
	var cur_month = cur_date.getMonth() + 1;
	var real_date = cur_date.getDate();
	cur_month = cur_month > 9 ? cur_month : ("0" + cur_month);
	real_date = real_date > 9 ? real_date : ("0" + real_date);
	eT = cur_year + "-" + cur_month + "-" + real_date;
	if (pdVal == 1) {
		trans_day = addByTransDate(eT, 1);
	} else if (pdVal == -1) {
		trans_day = reduceByTransDate(eT, 1);
	} else {
		trans_day = eT;
	}
	//处理
	return trans_day;
}</span>

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;
  }
  
  //获得上一年在昨天这一天的日期
  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;
  }


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值