目标:我想使用Date()将接下来的12周中一周的最后一天(星期日)转换为单独的字符串
我有下面给我的正确的日期格式。我只需要关于实现我目标的最佳解决方案的建议。
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date(0);
System.out.println(dateFormat.format(date)); 发布于 2013-03-28 10:23:00
Java的日期系统让我感到困惑,但我认为您应该这样做:
1)做一个GregorianCalendar,而不是约会。
2) Calendar.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY)以获取本周星期日的日期。
3)在for循环中,将7天添加到日历中12次。对每个循环执行一些操作(例如,使用getTime()从GregorianCalendar获取日期)
发布于 2013-03-28 12:20:55
试一试
GregorianCalendar c = new GregorianCalendar();
for (int i = 0; i < 12;) {
c.add(Calendar.DATE, 1);
if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println(DateFormat.getDateInstance().format(c.getTime()));
i++;
}
}发布于 2015-06-21 19:16:27
首先,一周的最后一天并不总是和星期天一样,因为这取决于你使用的是哪种语言环境。
如果您使用的是Java 8,那么解决方案非常简单:
LocalDate firstJanuary = LocalDate.parse("01/01/2015",
DateTimeFormatter.ofPattern("MM/dd/yyyy"));
//last day of the week
TemporalField fieldUS = WeekFields.of(Locale.US).dayOfWeek();
LocalDate lastDayOfWeek = firstJanuary.with(fieldUS,7);
System.out.println(lastDayOfWeek);
//sunday
LocalDate sunday = firstJanuary.with(DayOfWeek.SUNDAY);
System.out.println(sunday);要迭代到接下来的几周,只需使用:
sunday.plusWeeks(1);https://stackoverflow.com/questions/15673020
复制相似问题