javascript 日期常用的方法

郭文睿 2009-11-11

1:经常涉及到日期的换算比较:

代码如下:

<html> 
<head> 
<title></title> 
<script language="javascript"> 
function returnMaxDate(){ 
var datevalue1 = document.getElementById("date1").value; 
var datevalue2 = document.getElementById("date2").value; 
if(datevalue1 > datevalue2){ 
return datevalue1; 
}else{ 
return datevalue2; 
} 
} 
</script> 
</head> 
<body> 
<input type="text" name="date1" id="date1"> 
<input type="text" name="date2" id="date2"> 
</body> 
</html>

2:日期的格式判断

代码如下:

//yyyy-MM-dd 
if (!/^\d{4}\-\d\d?\-\d\d?/.test(datavalue1)) { 
alert("datevalue1的日期格式不合法") 
} 
3:换算星期(摘抄他人) 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date; 
public class TestDate { 
public static String getWeekFromDate(String sDate,int type){ 
if("".equals(sDate)){ 
return ""; 
} 
SimpleDateFormat df = null; 
if(type==0){ 
df = new SimpleDateFormat("yyyy-MM-dd"); 
}else if(type==1){ 
df = new SimpleDateFormat("yyyyMMdd"); 
} 
Date date = null; 
try{ 
date = df.parse(sDate); 
}catch(ParseException e){ 
e.printStackTrace(); 
} 
Calendar cd = Calendar.getInstance(); 
cd.setTime(date); 
int mydate = cd.get(Calendar.DAY_OF_WEEK); 
String showDate = ""; 
switch (mydate) { //mydate分别是 1---7:星期日,星期一,星期二。。。 
case 1: 
showDate = "星期日"; 
break; 
case 2: 
showDate = "星期一"; 
break; 
case 3: 
showDate = "星期二"; 
break; 
case 4: 
showDate = "星期三"; 
break; 
case 5: 
showDate = "星期四"; 
break; 
case 6: 
showDate = "星期五"; 
break; 
default: 
showDate = "星期六"; 
break; 
} 
return showDate; 
} 
}

相关推荐