欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 和javascript 获取当前日期时间和本周日期时间 .

程序员文章站 2022-06-10 19:47:44
...

今天在项目中统计一周内的新站入网数,所以要获取当前日期时间,并由当前日期获取本周的日期,在网上查了一下,将简便的方法记录下来,以便日后有需要。

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>