日期:2014-05-16  浏览次数:20482 次

JS 关于时间的对比
用js来获取服务器时间。

    
var today = document.getElementById("today").value;
str1 =  today.replace(/-/g,"/");
var date2 = new Date(str1);
var a = new Date;
a = date2.getFullYear()+ "-"+(date2.getMonth()+1)+"-"+date2.getDate(); 
//JSP面页上有INPUT隐藏文本框 数值是从后台NEW了个DATE 服务器时间
	
for(var i=1;i<6;i++){
    if(document.getElementById(i)){
    var formDate = document.getElementById(i).value;
    str =  formDate.replace(/-/g,"/");
    var date1 = new Date(str);
    var b = new Date;
    b = date1.getFullYear()+ "-"+(date1.getMonth()+1)+"-"+date1.getDate(); 
    var d1=toDate(b);
    var d2=toDate(a);
if(b>a){
//处理结果
 }
else{
//处理结果
}	

function toDate(str){
    var sd=str.split("-");
    return new Date(sd[0],sd[1],sd[2]);
}

 


JSP页面比较时间:(从JSP页面异步传入)
<%@ page language="java" import="java.util.*,java.text.SimpleDateFormat" pageEncoding="utf-8"%>
<%
String date1 = request.getParameter("str");
Date date2 = new Date();
date2 = System.DateTime.Now.ToString("yyyy-MM-dd");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String today = df.format(date2);
Date time1 = null;
Date time2 = null;
time1 = df.parse(date1); 
time2 = df.parse(today); 
long l1=time1.getTime(); 
long l2=time2.getTime();
if(l1<l2){
	out.print("1");
}else {
	out.print("2");
}
%>


补:异步代码:
<script type="text/javascript">
if (window.ActiveXObject && !window.XMLHttpRequest) { 
	  window.XMLHttpRequest=function() { 
	    return new ActiveXObject('Microsoft.XMLHTTP'); 
	  }; 
	}
function dateCompare(date,i){
var req=new XMLHttpRequest(); 
if (req) { 
  req.onreadystatechange=function() { 
    if (req.readyState==4 && req.status==200) {//判断状态,4是已发送,200已完成 
    	if(1==req.responseText){
    	//处理结果
      }else if(2==req.responseText) {
	//处理结果
          }
    }
  } 
  req.open('POST', '${pageContext.request.contextPath}/iepiao/datecompare.jsp?str='+date);
  req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
  req.send(""); //发送参数如果有参数req.send("username="+user_name);用request取得 
}
}
</script>


JS时间比较(精确到秒 FRIEFOX兼容)
<script language="javascript"> 
function ticketindex(){
    
    var today = document.getElementById("today").value;
    str1 =  today.replace("-", "/").replace("-", "/");
    for(var i=1;i<6;i++){
       if(document.getElementById(i)){
	var formDate = document.getElementById(i).value;
	//结束时间	   
         var formDate2 = document.getElementById("start"+i).value;
         //开始时间
	str =  formDate.replace("-", "/").replace("-", "/");
	str2 =  formDate2.replace("-", "/").replace("-", "/");
	var pare1 =(Date.parse(str)-Date.parse(str1))/3600/1000;
         var pare2 =(Date.parse(str1)-Date.parse(str2))/3600/1000;
           //alert(pare1+"   "+pare2);
		   if(pare1>0 && pare2>0){
	    	  //处理结果	       }
	       else{
	    	   //处理结果	       }
	  }
   }
}