Calender.getTime()总是在Calender.set(Calender.TIME_ARG,time)之后返回类似的值

时间:2017-06-26 15:11:01

标签: java android

我已经编写了函数来帮助我将周界返回到周和年的选定值的一周,但是我继续为每个变量周获得相同的界限,并且我将传递给该方法。

public static String getWeekBounds(int year, int week){
    Calendar c = Calendar.getInstance();
    c.set(Calendar.WEEK_OF_YEAR, week);
    c.set(Calendar.YEAR, year);
    int firstDayOfWeek = c.getFirstDayOfWeek();
    c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
    String result = new SimpleDateFormat("dd-MM-yy",Locale.getDefault()).format(c.getTime()) + "~";
    int lastDayOfWeek = firstDayOfWeek+6;
    c.set(Calendar.DAY_OF_WEEK, lastDayOfWeek);
    result += new SimpleDateFormat("dd-MM-yy",Locale.getDefault()).format(c.getTime());

    return result;
}

我希望函数返回正确的周界限值。

2 个答案:

答案 0 :(得分:0)

您可以在一周的第一天以这种方式执行此操作:

Calendar c = Calendar.getInstance();
c.set(Calendar.WEEK_OF_YEAR, week);
c.set(Calendar.YEAR, year);          
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
System.out.println(sdf.format(c.getTime()));

以及一周的最后一天

c.set(Calendar.WEEK_OF_YEAR, week+1);
c.add(Calendar.DAY_OF_YEAR, -1);
System.out.println(sdf.format(c.getTime()));

答案 1 :(得分:0)

在设置时间以确认已设置的值之后调用c.getTime()的逻辑是解决了我的问题。

public static String getWeekBounds(int year, int week){
    Calendar c = Calendar.getInstance();
    c.set(Calendar.WEEK_OF_YEAR, week);
    c.set(Calendar.YEAR, year);
    c.getTime(); //line added that removed the glitch
    int firstDayOfWeek = c.getFirstDayOfWeek();
    c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
    String result = new SimpleDateFormat("dd-MM-yy",Locale.getDefault()).format(c.getTime()) + "~";
    int lastDayOfWeek = firstDayOfWeek+6;
    c.set(Calendar.DAY_OF_WEEK, lastDayOfWeek);
    result += new SimpleDateFormat("dd-MM-yy",Locale.getDefault()).format(c.getTime());

    return result;
}