在最近的一个OA中,我需要判断两个日期是否是同一周,根据一个给定的日期获得所属周的周一和周五的日期。
在完成以上任务时,我发现Calendar 的确是一个功能强大的class。
下面给出源码,供兄弟们参考指正。
/*
* 创建日期 2005-3-30
package com.infoearth;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @李春雷
*
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 void main(String[] args){
}
}
本文地址:http://com.8s8s.com/it/it10551.htm