java - 获取特定月份的天数

标签 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);
}

最佳答案

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

相关文章:

java - 从父类(super class)型转换回子类型

java - 各种类型文件的哈希值

java - Android 警报立即触发

java - 带有更新图像的 JLabel 刷新图标

java - 无法在 AWS pinpoint 上发送语音消息

java - 编译 64 位 Java 程序 -server vs -d64

java - 使用 Spring security Javaconfig 进行基本和基于表单的身份验证

java - 创建文件中定义的名称为 'userController' 的 bean 时出错

java - 强制用户提供两个答案之一?

java - 发送通知到通知栏