如何使用 java.util.Calendar 获取特定月份的天数。 我已经尝试过下面给出的代码,但它给了我最近一个月的天数,而不是我作为输入给出的月份。 我不想使用开关盒。 有人可以帮忙吗? 提前致谢!
public static void main(String args[]) throws ParseException {
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
if (month == 0) {
month = 3;
year = year-1;
}
String dateStart = "'" + (year) + "-" + (month) + "-1 00:00:00'";
String dateEnd = "'" + (year) + "-" + (month) + "-"
+ cal.getMaximum(Calendar.DAY_OF_MONTH);
dateEnd = dateEnd + " 23:59:59'";
System.out.println("Start and End Date : " + dateStart + " : " + dateEnd);
}
最佳答案
这是如何使用 java.time
获取给定 int 月份
和 int 年
的日期的示例,
看看评论:
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int month = 1;
int year = 2018;
// create something that stores the days and keeps them sorted, preferably
Set<LocalDate> allDaysOfGivenMonth = new TreeSet<LocalDate>();
// stream the days from first to last day of the given month
IntStream.rangeClosed(1, YearMonth.of(year, month).lengthOfMonth())
.mapToObj(day -> LocalDate.of(year, month, day)) // map them to LocalDate objects
.forEach(localDate -> allDaysOfGivenMonth.add(localDate)); // and store each of them
// afterwards, just print them for a first glance...
allDaysOfGivenMonth.forEach(localDate -> {
System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE) + " - "
+ localDate.getDayOfWeek()
.getDisplayName(TextStyle.FULL_STANDALONE, Locale.getDefault()));
});
}
}
关于java - 获取特定月份的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54455418/