java 获取前一周星期天的日期,例如今天2013-8-1,上一周星期日就是2013-7-28

2024-11-26 06:48:02
推荐回答(2个)
回答1:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TestDate {
    public static void main(String[] args) {
        // 设置当前日期
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(new Date());
        // 取当前日期是星期几(week:星期几)
        int week = aCalendar.get(Calendar.DAY_OF_WEEK);
        if (week == 1) {
            week = 7;
        } else if (week == 0) {
            week = 6;
        } else {
            week -= 1;
        }
        // 取距离当前日期最近的周日与当前日期相差的天数(count:相差的天数。正数:之后的周日,负数:之前的周日)
        int count = 0;
        if (week <= 3) {
            count = -week;
        } else if (week >= 4) {
            count = 7 - week;
        }
        // 获取距离当前日期最近的周日日期
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd EE");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_WEEK, count);
        // 格式化并打印出距离当前日期最近的周日日期
        System.out.println("当前日期: " + df.format(aCalendar.getTime()) + '\n' + "最近周日: " + df.format(c.getTime()));
    }
}

回答2:

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class $ {

    public static void main(String[] args) {

        Format f = new SimpleDateFormat("yyyy-MM-dd");

        Calendar c = Calendar.getInstance();
        System.out.println("今天是:" + f.format(c.getTime()));

        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

        int lastSunday = 7 - dayOfWeek + 1;

        c.set(Calendar.DAY_OF_MONTH, -lastSunday);
        System.out.println("上周日是:" + f.format(c.getTime()));
    }
}

今天是:2013-08-01
上周日是:2013-07-28