java - 获取特定月份的天数
问题描述
如何使用 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);
}
解决方案
这是一个如何获取给定int month
和int year
使用天数的示例java.time
,
请查看评论:
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()));
});
}
}
推荐阅读
- verilog - Verilog 8 位处理器代码中的锁存器生成警告
- javascript - 到处使用异步函数的(潜在)缺点是什么?
- java - 静态变量及其值的继承如何工作?
- java - 无法在按钮中重新缩放可绘制对象
- java - Java执行网页
- reactjs - 反应路由器:空白页
- google-cloud-platform - Apache Beam GroupByKey 似乎没有输出任何东西
- php - php - 按点排序,然后按字母顺序
- java - 如何创建 FindByIndexNameSessionRepository 的 bean
- ios - 为什么MKTileOverlay在ios,swift4中一遍又一遍地为openstreet地图重复相同的图块