public static void main(String[] args) {
SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(smf.format(new Date()));
Date d = lastMonday();
System.out.println(smf.format(d));
Date l = lastLastMonday();
System.out.println(smf.format(l));
}
/**
* 获取上周天时间
*/
public static Date lastMonday() {
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DAY_OF_WEEK, -1);
}
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
int offset = 1 - dayOfWeek;
return getFirstDayOfWeek(calendar.getTime(), 1);
}
/**
* 获取下周天时间
*/
public static Date nextMonday() {
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DAY_OF_WEEK, -1);
}
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
int offset = 1 - dayOfWeek;
return getFirstDayOfWeek(calendar.getTime(), 1);
}
/**
* 获取上上周天时间
*/
public static Date lastLastMonday() {
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DAY_OF_WEEK, -1);
}
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
int offset = 1 - dayOfWeek;
calendar.add(Calendar.DATE, offset - 7);
return getFirstDayOfWeek(calendar.getTime(), 1);
}
/**
* 得到某一天的该星期的第一日 00:00:00
*
* @param date
* @param firstDayOfWeek
* 一个星期的第一天为星期几
*
* @return
*/
public static Date getFirstDayOfWeek(Date date, int firstDayOfWeek) {
Calendar cal = Calendar.getInstance();
if (date != null)
cal.setTime(date);
cal.setFirstDayOfWeek(firstDayOfWeek);//设置一星期的第一天是哪一天
cal.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);//指示一个星期中的某天
cal.set(Calendar.HOUR_OF_DAY, 0);//指示一天中的小时。HOUR_OF_DAY 用于 24 小时制时钟。例如,在 10:04:15.250 PM 这一时刻,HOUR_OF_DAY 为 22。
cal.set(Calendar.MINUTE, 0);//指示一小时中的分钟。例如,在 10:04:15.250 PM 这一时刻,MINUTE 为 4。
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
本文介绍如何使用Java中的SimpleDateFormat格式化日期,并提供了获取当前日期、上周一及上上周一日期的具体实现。
210

被折叠的 条评论
为什么被折叠?



