如果在java中提供了开始日期和结束日期,那么如何生成日期?
如下:
例如:如果{i}}和start date is 15-04-2012
有这个我想要的日期如下,则列表应省略end date is 15-06-2012
和saturday
sunday
1.15-04-2012,
2.16-04-2012,
3.17-04-2012,
.
.
.
.
.
.
我已经完成了以下操作,但如果日期范围是同月,它将生成一个月。 `
15-06-2012
所以请建议我如何去做。
此致 贝
答案 0 :(得分:4)
int noOfDaysBetween = 5;
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
for(int index = 0 ; index < noOfDaysBetween; index++){
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if( dayOfWeek!=Calendar.SUNDAY && dayOfWeek!=Calendar.SATURDAY) {
System.out.println(cal.getTime());
}
cal.add(Calendar.DATE, 1);
}
答案 1 :(得分:1)
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
//15-04-2012
calendar.set(Calendar.DAY_OF_MONTH, 15);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MONTH, 3);
Date start = calendar.getTime();
//15-06-2012
calendar.set(Calendar.MONTH, 5);
Date end = calendar.getTime();
calendar.setTime(start);
Date d = null;
while((d = calendar.getTime()).before(end) || d.equals(end)) {
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (day != Calendar.SATURDAY && day != Calendar.SUNDAY) {
System.out.println(d);
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
}
答案 2 :(得分:1)
我更喜欢使用LocalDate。
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Game {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2018, 6, 1);
LocalDate end = LocalDate.of(2018, 8, 1);
LocalDate d = start;
while(d.compareTo(end) <= 0) {
if (d.getDayOfWeek() != DayOfWeek.SATURDAY && d.getDayOfWeek() != DayOfWeek.SUNDAY) {
System.out.println(d);
}
d = d.plusDays(1);
}
}
}
答案 3 :(得分:0)
使用以下joda-time
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
public class DatesexcludingWeekend {
public static void main(String[] args) {
final LocalDate start = new LocalDate(2012, 06, 15);
final LocalDate end = new LocalDate(2012, 07, 14);
LocalDate weekday = start;
if (start.getDayOfWeek() == DateTimeConstants.SATURDAY|| start.getDayOfWeek() == DateTimeConstants.SUNDAY) {
weekday = weekday.plusWeeks(1).withDayOfWeek(DateTimeConstants.MONDAY);
}
while (weekday.isBefore(end)) {
System.out.println(weekday);
if (weekday.getDayOfWeek() == DateTimeConstants.FRIDAY)
weekday = weekday.plusDays(3);
else
weekday = weekday.plusDays(1);
}
}