Java 每周两个月

Java 每周两个月,java,android,calendar,Java,Android,Calendar,我对android日历编程有一个问题,所以 若一周有两个月,安卓会给我写上旧月的名字。我想让他写一些像《旧月新月》的东西 我的代码如下 Calendar wek = Calendar.getInstance(Locale.US); wek.add(Calendar.WEEK_OF_YEAR,r); SimpleDateFormat gm = new SimpleDateFormat("MMM yyy"); mes.setText(gm.format(wek.getTime())); 你认为正确

我对android日历编程有一个问题,所以 若一周有两个月,安卓会给我写上旧月的名字。我想让他写一些像《旧月新月》的东西

我的代码如下

Calendar wek = Calendar.getInstance(Locale.US);
wek.add(Calendar.WEEK_OF_YEAR,r);
SimpleDateFormat gm = new SimpleDateFormat("MMM yyy");
mes.setText(gm.format(wek.getTime()));

你认为正确的月份是什么?你要做的就是在现在的确切时刻加上r周。这是特定的时间点,与特定的毫秒相关。这个毫秒属于一个月或另一个月。您的代码将返回该月份。

您应该获取一周中第一天和最后一天的索引,并检查它们所属的月份


我不是以英语为母语的人,但你可以说一周与两个月重叠,超过两个月的一周。

之所以这样做,是因为当查看以一周表示的日期时,它只查看一周中的第一天。您需要手动检查一周的第一天和最后几天,如果它们在不同的月份,则手动设置日期的格式。你还需要注意与年份重叠的一周。大概是这样的:

Calendar wek = Calendar.getInstance(Locale.US);
wek.add(Calendar.WEEK_OF_YEAR,r);

//this will set your calendar onto the first day of the week
int w = wek.get(Calendar.WEEK_OF_YEAR);
int y = wek.get(Calendar.YEAR);
wek.clear();
wek.set(Calendar.YEAR, y);
wek.set(Calendar.WEEK_OF_YEAR, w);
//get the month and year of the first day of the week
int m1 = wek1.get(Calendar.MONTH);
int y1 = wek1.get(Calendar.YEAR);

//get the date for the end of the week and its month and year
Calendar w2 = wek;
w2.add(Calendar.DATE, 6);
int m2 = w2.get(Calendar.MONTH);
int y2 = w2.get(Calendar.YEAR);

if(m1 == m2) {
    //if the two months are the same, then just format the date
    SimpleDateFormat gm = new SimpleDateFormat("MMM yyyy");
    mes.setText(gm.format(wek.getTime()));
}
else if(y1 == y1) {
    //different months, same year - format as "MMM - MMM yyyy"
    SimpleDateFormat gm = new SimpleDateFormat("MMM");
    SimpleDateFormat gy = new SimpleDateFormat("yyyy");
    mes.setTextText(gm.format(wek.getTime()) + " - " +
                    gm.format(w2.getTime()) + " " +
                    gy.format(wek.getTime()));
}
else {
    //Different months and different years - format as "MMM yyyy - MMM yyyy"
    SimpleDateFormat gm = new SimpleDateFormat("MMM yyyy");
    mes.setTextText(gm.format(wek.getTime()) + " - " +
                    gm.format(w2.getTime()));
}