简体   繁体   English

获取当月日历中的所有日期

[英]Get all dates in calendar in current month

在此处输入图片说明

How to get all dates in the calendar in current/some month?如何获取当前/某个月日历中的所有日期? for example for this month, like the picture比如这个月,如图

So the result is ["07-31-2016", "08-01-2016", "08-02-2016" ... "08-31-2016", "09-01-2016", "09-02-2016", "09-03-2016"]所以结果是 ["07-31-2016", "08-01-2016", "08-02-2016" ... "08-31-2016", "09-01-2016", "09- 02-2016", "09-03-2016"]

Any ideas?, thanks in advance.任何想法?,提前致谢。

Well, with Calendar and its constants you can achieve this quite easy:好吧,使用Calendar及其常量,您可以很容易地实现这一点:

Given month and year get first day of the month and place calendar on monday:给定monthyear获取month第一天并将日历放在星期一:

Calendar start = Calendar.getInstance();
start.set(MONTH, month - 1);  // month is 0 based on calendar
start.set(YEAR, year);
start.set(DAY_OF_MONTH, 1);
start.getTime();   // to avoid problems getTime make set changes apply
start.set(DAY_OF_WEEK, SUNDAY);
if (start.get(MONTH) <= (month - 1))  // check if sunday is in same month!
    start.add(DATE, -7);

Given month and year get last day of month and move calendar to sunday给定monthyear获取month最后一天并将日历移至星期日

Calendar end = Calendar.getInstance();
end.set(MONTH, month);  // next month 
end.set(YEAR, year);
end.set(DAY_OF_MONTH, 1);
end.getTime();   // to avoid problems getTime make set changes apply
end.set(DATE, -1);
end.set(DAY_OF_WEEK, SATURDAY);
if (end.get(MONTH) != month)  
    end.add(DATE, + 7);

Test it:测试一下:

public static void main(String[] args) {
    int month = 8, year = 2016; 

    Calendar start = Calendar.getInstance();
    start.set(MONTH, month - 1);  // month is 0 based on calendar
    start.set(YEAR, year);
    start.set(DAY_OF_MONTH, 1);
    start.getTime();
    start.set(DAY_OF_WEEK, SUNDAY);
    if (start.get(MONTH) <= (month - 1))  
        start.add(DATE, -7);

    System.out.println(printCalendar(start));

    Calendar end = Calendar.getInstance();
    end.set(MONTH, month);  // next month 
    end.set(YEAR, year);
    end.set(DAY_OF_MONTH, 1);
    end.getTime();
    end.set(DATE, -1);
    end.set(DAY_OF_WEEK, SATURDAY);
    start.getTime();
    if (end.get(MONTH) != month)  
        end.add(DATE, + 7);

    System.out.println(printCalendar(end));
}

Combined with:结合:

import static java.util.Calendar.*;

and

private final static SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
private static String printCalendar(Calendar c) {
    return df.format(c.getTime()); 
}

OUTPUT:输出:

2016/07/31
2016/09/03

WITH

int month = 5, year = 2015; 

OUTPUT:输出:

2015/04/26
2015/06/06

Now, just iterate over starting Calendar adding +1 to Calendar.DATE in a while loop (in the example I split by weeks to be more clear):现在,只需在while循环中迭代开始Calendar+1添加到Calendar.DATE (在示例中,我按周拆分以便更清楚):

int i = 1;
while (start.before(end)) {
    System.out.print(printCalendar(start));
    if (i % 7 == 0) {   // last day of the week
        System.out.println();
        i  = 1;
    } else {
        System.out.print(" - ");
        i++;
    }
    start.add(DATE, 1);
}

OUTPUT:输出:

2015/04/26 - 2015/04/27 - 2015/04/28 - 2015/04/29 - 2015/04/30 - 2015/05/01 - 2015/05/02
2015/05/03 - 2015/05/04 - 2015/05/05 - 2015/05/06 - 2015/05/07 - 2015/05/08 - 2015/05/09
2015/05/10 - 2015/05/11 - 2015/05/12 - 2015/05/13 - 2015/05/14 - 2015/05/15 - 2015/05/16
2015/05/17 - 2015/05/18 - 2015/05/19 - 2015/05/20 - 2015/05/21 - 2015/05/22 - 2015/05/23
2015/05/24 - 2015/05/25 - 2015/05/26 - 2015/05/27 - 2015/05/28 - 2015/05/29 - 2015/05/30
2015/05/31 - 2015/06/01 - 2015/06/02 - 2015/06/03 - 2015/06/04 - 2015/06/05 - 2015/06/06

java.time时间

You can use the nice java.time classes built into Java 8 and later.您可以使用 Java 8 及更高版本中内置的优秀 java.time类。 Both the above solutions work, this is a way to do in Java 8. Can be done with a little more brevity , split it just for understanding.上述两种解决方案都有效,这是 Java 8 中的一种方法。可以更简洁一些,将其拆分以供理解。

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

public class Clazz {
    public static void main(String[] args) throws Exception {
        LocalDate today = LocalDate.now();
        LocalDate firstDayOfTheMonth = today.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDayOfTheMonth = today.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate squareCalendarMonthDayStart = firstDayOfTheMonth
                .with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
        LocalDate squareCalendarMonthDayEnd = lastDayOfTheMonth
                .with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY));
        List<LocalDate> totalDates = new ArrayList<>();
        while (!squareCalendarMonthDayStart.isAfter(squareCalendarMonthDayEnd)) {
            totalDates.add(squareCalendarMonthDayStart);
            squareCalendarMonthDayStart = squareCalendarMonthDayStart.plusDays(1);
        }

        totalDates.forEach(System.out::println);
    }
}

Get the monday before the 1st of that month:获取该月 1 号之前的星期一:

Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(2016, 08, 01);

Calendar start = Calendar.getInstance();
start.setFirstDayOfWeek(Calendar.MONDAY);
start.setWeekDate(2016,c.getWeekYear(), Calendar.MONDAY);

Get the sunday after the last day of that month:获取该月最后一天之后的星期日:

c.set(2016,08,31);
Calendar end = Calendar.getInstance();
end.setFirstDayOfWeek(Calendar.MONDAY);
end.setWeekDate(2016, c.getWeekYear(), Calendar.SUNDAY);

Then print all dates between start and end然后打印开始和结束之间的所有日期

Write a common method like this and use it -写一个这样的常用方法并使用它 -

 fun getAllDateOfCurrentMonth(): List<LocalDate> {
            val yearMonth= YearMonth.now()
            val firstDayOfTheMonth = yearMonth.atDay(1)
            val datesOfThisMonth = mutableListOf<LocalDate>()
            for (daysNo in 0 until yearMonth.lengthOfMonth()){
                datesOfThisMonth.add(firstDayOfTheMonth.plusDays(daysNo.toLong()))
            }
            return datesOfThisMonth
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM