1. 程式人生 > >java 和javascript 獲取當前日期時間和本週日期時間 .

java 和javascript 獲取當前日期時間和本週日期時間 .

import java.util.Calendar;
public class Test {
	public static void main(String[] args) {	
		Calendar cal =Calendar.getInstance();
                  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                 cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); //獲取本週一的日期
                 System.out.println(df.format(cal.getTime()));
		//這種輸出的是上個星期週日的日期,因為老外那邊把週日當成第一天
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		//增加一個星期,才是我們中國人理解的本週日的日期
		cal.add(Calendar.WEEK_OF_YEAR, 1);
	         System.out.println(df.dateFormat(cal.getTime()));
	}

}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>獲取當前周</title>
</head>

<body>
</body>
</html>
<script type="text/javascript">
function test(){
 var date=new Date();
 var date2=new Date();
 var day=date.getDay();
 var ms=date.getMilliseconds();
 var Mon,Sun;
 var tmp=1000*60*60*24;
 switch(day){
  case 0:
   Mon=ms-6*tmp;
   Sun=ms;
  break;
  case 1:
   Mon=ms;
   Sun=ms+6*tmp;
  break;
  case 2:
   Mon=ms-1*tmp;
   Sun=ms+5*tmp;
  break;
  case 3:
   Mon=ms-2*tmp;
   Sun=ms+4*tmp;
  break;
  case 4:
   Mon=ms-3*tmp;
   Sun=ms+3*tmp;
  break;
  case 5:
   Mon=ms-4*tmp;
   Sun=ms+2*tmp;
  break;
  case 6:
   Mon=ms-5*tmp;
   Sun=ms+1*tmp;
  break;
 }
date.setMilliseconds(Mon);
document.write("週一"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+"<br />");
document.write("週二"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+(date.getDate()+1)+"<br />");
document.write("週三"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+(date.getDate()+2)+"<br />");
document.write("週四"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+(date.getDate()+3)+"<br />");  
document.write("週五"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+(date.getDate()+4)+"<br />");
document.write("週六"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+(date.getDate()+5)+"<br />");	  
date2.setMilliseconds(Sun);
 document.write("週日"+date2.getFullYear()+"-"+(date2.getMonth()+1)+"-"+date2.getDate());
}
test()
</script>