如何使用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);
}
答案 0 :(得分:1)
这是一个如何使用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()));
});
}
}
答案 1 :(得分:0)
我在上面的评论中使用了这种逻辑,但我不理解其背后的逻辑,谁能为我解释一下它的逻辑
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 = 6;
year = year-1;
}
String dateStart = "'"+(year)+"-"+(month)+"-1 00:00:00'";
cal.set(Calendar.MONTH, 5);
cal.set(Calendar.DAY_OF_MONTH, 6);
cal.set(Calendar.YEAR, 2019);
String dateEnd = "'"+(year)+"-"+(month)+"-"+cal.getActualMaximum(Calendar.DAY_OF_MONTH);
dateEnd = dateEnd+" 23:59:59'";
System.out.println("Start and End Date : "+dateStart+" : "+dateEnd);
}