首页 > 解决方案 > 获取特定月份的天数

问题描述

如何使用 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

解决方案


这是一个如何获取给定int monthint 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()));
        });
    }

}

推荐阅读