从特定日期获取上周一和下周的日期

时间:2015-04-15 13:31:32

标签: java android date

我星期一和我约会。如果我点击上一个和下一个星期一,如果我在java中单击下一个,我想找到星期一上周的日期。我正在寻找一种方法来增加我的约会七天。

3 个答案:

答案 0 :(得分:3)

您可以使用日历类: 这是示例

String dt = "2015-04-13";  // Current monday date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
if(next){
  c.add(Calendar.DATE, 7);  // for next Monday
}else{ 
  c.add(Calendar.DATE, -7);  // for previous Monday
}
dt = sdf.format(c.getTime());  // dt is now the new date

答案 1 :(得分:0)

Calendar calendar = Calendar.getInstance();
calendar.set(2015, Calendar.April, 15);//Given date
System.out.printf("Starting day ", calendar);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.add(Calendar.DATE, 7);//for next
calendar.add(Calendar.DATE, -7);//for previous

答案 2 :(得分:0)

这可以为您提供所需的结果。

public static void main(String[] args) 
{
    String date = "2015-04-13";  // Current Monday date.

    System.out.println(process(date, "next"));
    System.out.println(process(date, "PREVIOUS"));
    System.out.println(process(date, "next"));
}

private static String process(String date, String operation)
{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Calendar calendar = Calendar.getInstance(); //create new calendar instance
    calendar.clear(); //clear the current information on the calendar instance
    calendar.setLenient(false);

    try {
        calendar.setTime(sdf.parse(date)); //parse current Monday date and set as calendar date/time
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if("NEXT".equalsIgnoreCase(operation)) {
        calendar.add(Calendar.DATE, 7);  // for next Monday
    }

    if("PREVIOUS".equalsIgnoreCase(operation)) {
        calendar.add(Calendar.DATE, -7);  // for previous Monday
    }

    return sdf.format(calendar.getTime()); //format the calendar date/time
}