# 关于Java日期处理函数

365/7=52余1

1、每过去1年多1天，闰年再多1天，到上一年为止多了几天能算了吧。
int count=(A-1)+(A-1)/4+(A-1)/400-(A-1)/100;

2、从1月到上月今年过去的总天数，列个全年的数组能行吧(没考虑今年的闰月）
int[] M={31,28,31,30,31,30,31,31,30,31,30,31};
for(int i=1;i count+=M[i];
}

3、如果今年是闰年且B>2
count++

4、到本月今天总天数
count+=C;

5、由于公元1年1月1日是星期一，再扣一天除7取余
(count-1)%7
0为星期天，以此类推

import java.util.Calendar;
import java.util.Date;

public class CountWeek {

public static String getWeekOfDate(Date dt){
String[] weekDays={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
Calendar cal=Calendar.getInstance();
cal.setTime(dt);

int w=cal.get(Calendar.DAY_OF_WEEK)-1;
if(w<0)w=0;
return weekDays[w];

}
public static void main(String[] args) {
System.out.println("今天是："+CountWeek.getWeekOfDate(new Date()));
}
}

public class ManageWeek {
//判断两个日期是否在同一周
boolean isSameWeekDates(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
if (0 == subYear) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
}
else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
}
else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
}
return false;
}

//产生周序列
public static String getSeqWeek(){
Calendar c = Calendar.getInstance(Locale.CHINA);
String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
if(week.length()==1)week = "0" + week;
String year = Integer.toString(c.get(Calendar.YEAR));
return year+week;

}

//获得周一的日期
public static String getMonday(Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}

//获得周五的日期
public static String getFriday(Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK,Calendar.FRIDAY);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}

//当前日期前几天或者后几天的日期

public static String afterNDay(int n){
Calendar c=Calendar.getInstance();
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
c.setTime(new Date());
Date d2=c.getTime();
String s=df.format(d2);
return s;
}

public static void main(String[] args){

}

}

[@more@]

• 博文量
11
• 访问量
18073