Java 如何使用日历类获取一个月中的所有日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20089549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get all the dates in a month using calender class?
提问by Android_dev
Here I want to display dates like
在这里我想显示日期
2013-01-01,
2013-01-02,
2013-01-03,
.
.
...etc
I can get total days in a month
我可以得到一个月的总天数
private int getDaysInMonth(int month, int year) {
Calendar cal = Calendar.getInstance(); // or pick another time zone if necessary
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1); // 1st day of month
cal.set(Calendar.YEAR, year);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
Date startDate = cal.getTime();
int nextMonth = (month == Calendar.DECEMBER) ? Calendar.JANUARY : month + 1;
cal.set(Calendar.MONTH, nextMonth);
if (month == Calendar.DECEMBER) {
cal.set(Calendar.YEAR, year + 1);
}
Date endDate = cal.getTime();
// get the number of days by measuring the time between the first of this
// month, and the first of next month
return (int)((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
}
Does anyone have an idea to help me?
有没有人有想法可以帮助我?
采纳答案by Jean B
If you only want to get the max number of days in a month you can do the following.
如果您只想获得一个月中的最大天数,您可以执行以下操作。
// Set day to one, add 1 month and subtract a day
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.get(Calendar.DAY_OF_MONTH);
If you actually want to print every day then you can just set the day of month to 1 and keep adding a day in a loop until the month changes.
如果你真的想每天打印,那么你可以将月份的日期设置为 1 并在循环中继续添加一天,直到月份发生变化。
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
int myMonth=cal.get(Calendar.MONTH);
while (myMonth==cal.get(Calendar.MONTH)) {
System.out.print(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 1);
}
回答by scottb
A couple of comments...
一些评论...
Firstly, "... Calendar objects are particularly expensive to create." (J. Bloch, Effective Java, 2nd Ed.). If this is a method that you are going to be calling frequently, consider that you do not need to create a new Calendar object every time you call it.
首先,“...日历对象的创建成本特别高。” (J. Bloch,Effective Java,第 2 版)。如果这是您将经常调用的方法,请考虑您不需要每次调用它时都创建一个新的 Calendar 对象。
Consider using a Calendar object held in a private static field that is initialized with a static initializer block. This presumes a single-threaded solution and would require synchronization in a concurrent environment. Otherwise, it really ought to be possible to reuse the same Calendar for your calculations.
考虑使用保存在私有静态字段中的 Calendar 对象,该字段由静态初始化程序块初始化。这假定是单线程解决方案,并且需要在并发环境中进行同步。否则,真的应该可以重复使用相同的日历进行计算。
Secondly, while you can find that greatest value for the DAY_OF_MONTH by iterating over the possible valid values, I think you can let the API do it for you. Consider using the getMaximum(DAY_OF_MONTH) or getGreatestMaximum(DAY_OF_MONTH) methods of the Calendar class.
其次,虽然您可以通过迭代可能的有效值找到 DAY_OF_MONTH 的最大值,但我认为您可以让 API 为您完成。考虑使用 Calendar 类的 getMaximum(DAY_OF_MONTH) 或 getGreatestMaximum(DAY_OF_MONTH) 方法。
回答by Sudeepta
This will give you all days of a month.
这将为您提供一个月的所有日子。
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(df.format(cal.getTime()));
for (int i = 1; i < maxDay; i++) {
cal.set(Calendar.DAY_OF_MONTH, i + 1);
System.out.print(", " + df.format(cal.getTime()));
}
The first date is printed outside of loop for comma separated output.
第一个日期打印在循环之外以用于逗号分隔的输出。
回答by Ole V.V.
Modern answer: Don't use Calendar
. Use java.time, the modern Java date and time API.
现代答案:不要使用Calendar
. 使用 java.time,现代 Java 日期和时间 API。
YearMonth ym = YearMonth.of(2013, Month.JANUARY);
LocalDate firstOfMonth = ym.atDay(1);
LocalDate firstOfFollowingMonth = ym.plusMonths(1).atDay(1);
firstOfMonth.datesUntil(firstOfFollowingMonth).forEach(System.out::println);
Output (abbreviated):
输出(缩写):
2013-01-01 2013-01-02 2013-01-03 … 2013-01-30 2013-01-31
2013-01-01 2013-01-02 2013-01-03 … 2013-01-30 2013-01-31
datesUntil
gives us a stream of dates until the specified end date exclusive, so when we give it the 1st of the following month, we get exactly all the dates of the month in question. In this example case up to and including January 31.
datesUntil
为我们提供了日期的流,直到指定的结束日期排他性,所以当我们给它下一个月的1日,我们得到确切的所有月份的有关日期。在此示例中,截至并包括 1 月 31 日。
Link:Oracle tutorial: Date Timeexplaining how to use java.time
.
链接:Oracle 教程:解释如何使用java.time
.