在我的应用中,我想显示用户在本周的约会列表。要传递给API的参数是fromDate和toDate,以毫秒(long)为单位。我需要知道如何获得一周中最后一天的毫秒数(考虑周从星期日开始到周六结束)。
答案 0 :(得分:0)
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println("Start of this week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// start of the next week
cal.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("Start of the next week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
一周的最后一天加6!
答案 1 :(得分:0)
这可以通过将星期几作为星期日添加,然后再添加6天来实现。
// Get current time. You can reset hours/ minutes/ seconds it with default values which you want.
Calendar c = new GregorianCalendar(Locale.getDefault());
// Set first day of week
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
// Add 6 into that to get Saurday
c.add(Calendar.DAY_OF_WEEK, 6);
// Get millisenconds for Saturday
long millies = c.getTimeInMillis();
答案 2 :(得分:0)
请检查以下代码,以毫秒为单位获取即将到来的星期六。
public class NextSaturdayMain
{
public static void main(String[] args)
{
System.out.println(getSaturday(new Date()));
}
public static long getSaturday(Date today)
{
Calendar cal = Calendar.getInstance();
cal.setTime(today);
int dow = cal.get(Calendar.DAY_OF_WEEK);
while (dow != Calendar.SATURDAY) {
int date = cal.get(Calendar.DATE);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
if (date == getMonthLastDate(month, year)) {
if (month == Calendar.DECEMBER) {
month = Calendar.JANUARY;
cal.set(Calendar.YEAR, year + 1);
} else {
month++;
}
cal.set(Calendar.MONTH, month);
date = 1;
} else {
date++;
}
cal.set(Calendar.DATE, date);
dow = cal.get(Calendar.DAY_OF_WEEK);
}
System.out.println(cal.getTime());
return cal.getTimeInMillis();
}
private static int getMonthLastDate(int month, int year)
{
switch (month)
{
case Calendar.JANUARY:
case Calendar.MARCH:
case Calendar.MAY:
case Calendar.JULY:
case Calendar.AUGUST:
case Calendar.OCTOBER:
case Calendar.DECEMBER:
return 31;
case Calendar.APRIL:
case Calendar.JUNE:
case Calendar.SEPTEMBER:
case Calendar.NOVEMBER:
return 30;
default: // Calendar.FEBRUARY
return year % 4 == 0 ? 29 : 28;
}
}
}