我正在尝试在日历中更改DayofWeek,但似乎没有像我期望的那样工作。这是一个例子。我将日历时间设置为星期五时间,但是当我将Calendar.DAY_OF_WEEK设置为Calendar.SUNDAY时,它将向下移动到下周。由于Calendar.SUNDAY是默认的第一天,不应该将时间移回当周的开头吗?
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class GenericWeekdayOpenFunction implements TimePeriodFunction {
public static void main(String[] args) {
// Nov 8 is Friday
long time = DateUtilities.newDateTimeAsMillis(2013, 11, 8, 10, 00, 00);
System.out.println(DateUtilities.formatGmtDatetime(time));
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(time);
// move day of week to Sunday, expect date to be Nov 3
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(DateUtilities.formatGmtDatetime(calendar.getTimeInMillis())); // wrong
// move day of week to Friday, expect date to be Nov 8
calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println(DateUtilities.formatGmtDatetime(calendar.getTimeInMillis()));
}
}
输出:
08-11-2013 10:00:00.000
10-11-2013 10:00:00.000
08-11-2013 10:00:00.000
答案 0 :(得分:0)
您的方案在基本Calendar
类使用情况下正常工作:
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
Date d = new Date(113, 10, 8, 10, 0, 0);
c.setTimeInMillis(d.getTime());
System.out.println(c.getTime());
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(c.getTime());
c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println(c.getTime());
输出:
Fri Nov 08 10:00:00 IST 2013
Sun Nov 03 10:00:00 IST 2013
Fri Nov 08 10:00:00 IST 2013
请注意,Date(113, 10, 8, 10, 0, 0);
仅用于快速检查,但已弃用。尝试任何其他组合也可以正常工作。您可以尝试使用基本Calendar
API和打印日期,即
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
System.out.println(c.getTime());//current day
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(c.getTime());
第二个日期应该回到之前的星期日而不是即将到来的日期。如果它适合您,那么DateUtilities
实施可能会令人怀疑。
答案 1 :(得分:-1)
我认为方法set(int field, int value)
工作接近最近的一天(而不是同一周的DAY_OF_WEEK)。
但您可以使用add(int field, int amount)
函数add(Calendar.DATE, -5)
来执行此操作。