我的要求是在过去日期时获取一周的开始和结束日期。我搜索过,我找到了大量的答案,但与哪一个最好使用相混淆。在其中一个主题中,我找到了以下代码:
Calendar c = Calendar.getInstance();
c.setTime(new Date("8/16/2017"));
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println("day :" + dayOfWeek);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
System.out.println("start of week day :" + c.getTime());
输出:
day :4
start of week day :Sun Aug 13 00:00:00 EDT 2017
我在上面的代码输出中看到了一个错误。本周开始应该是8月14日星期一,但它显示在8月13日星期日。获取日期的开始日期和结束日期的任何建议都会动态地作为字符串传递。
- EDITED-- 我正在寻找 java代码,它返回日期过去的那一周的第一天和最后一天。
答案 0 :(得分:3)
import java.time.LocalDate;
import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
public class FirstAndLast
{
public static void main(String[] args)
{
LocalDate today = LocalDate.now();
LocalDate monday = today.with(previousOrSame(MONDAY));
LocalDate sunday = today.with(nextOrSame(SUNDAY));
System.out.println("Today: " + today);
System.out.println("Monday of the Week: " + monday);
System.out.println("Sunday of the Week: " + sunday);
}
}
答案 1 :(得分:1)
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY); //Line2
c.setTime(new Date("8/16/2017"));
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println("day :" + dayOfWeek);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
System.out.println("start of week day :" + c.getTime());
将第一周的第一天设置为星期一,如第2行所示。
现在输出
day :4
start of week day :Mon Aug 14 00:00:00 EDT 2017