Java - 打印指定给定月年范围内每个月的第一个和最后一个日期

Java - Print First and Last date for each month within specified given month-year range

如何首先打印所有月份以及在给定的指定月份-年份范围内的最后一个日期? 到目前为止,我有打印 1 整年示例的代码,如果在输入年份 2019 中提供,则打印所有 12 个月的第一个和最后一个日期。但我想要的是它应该在指定的月-年范围内打印值。

示例,

String input_StartMonthYear = "1-2019";
String input_EndMonthYear = "6-2020";


Expected Output:

firstDay-> 2019-1-1
lastDay-> 2019-1-31

firstDay-> 2019-2-1
lastDay-> 2019-2-28

---
---

firstDay-> 2020-6-1
lastDay-> 2020-6-30

代码:

import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;

public class GetDate_Firt_Last {

    static String input_Year = "2019";
    static String completeinput;
    static int totalmonths[] = {1,2,3,4,5,6,7,8,9,10,11,12};



    public static void main (String args[]) throws Exception
    {

        int m;
        for (m = 1;m <= totalmonths.length;m++)
        {
            completeinput = m + "-" + input_Year;


            SimpleDateFormat sdf = new SimpleDateFormat("MM-yyyy");
            Date date = sdf.parse(completeinput);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);



            getFirstDayOfTheMonth(cal);
            getLastDayOfTheMonth(cal);
            System.out.println();
        }

    }


    public static String getFirstDayOfTheMonth(Calendar cal) throws Exception {
        String firstDay;

        try {

            int firstDate = cal.getActualMinimum(Calendar.DATE);

            int month = cal.get(Calendar.MONTH) +1;
            int year = cal.get(Calendar.YEAR);
            firstDay = year + "-" + month + "-" + firstDate;
            System.out.println("firstDay-> " +firstDay);

        } catch (Exception e) {
            throw new Exception("Exception in getFirstDayOfTheMonth." + e.getMessage());
        }
        return firstDay;
    }





    public static String getLastDayOfTheMonth(Calendar cal) throws Exception {
        String lastDay;
        try {

            int lastDate = cal.getActualMaximum(Calendar.DATE);
            int month = cal.get(Calendar.MONTH)+1;
            int year = cal.get(Calendar.YEAR);

            lastDay = year + "-" + month + "-" + lastDate;
            System.out.println("lastDay-> "+ lastDay);
        } catch (Exception e) {
            throw new Exception("Exception in getLastDateOfTheMonth." + e.getMessage());
        }
        return lastDay;
    }


}

实际输出:

firstDay-> 2019-1-1
lastDay-> 2019-1-31

firstDay-> 2019-2-1
lastDay-> 2019-2-28

---
---

firstDay-> 2019-12-1
lastDay-> 2019-12-31

如果您使用 java 8 或更高版本,则可能是第一种方法

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

public class GetDate_Firt_Last {

    public static void main(String[] args) {
        String input_StartMonthYear = "1-2019";
        String input_EndMonthYear = "6-2020";
        
        DateTimeFormatter df = DateTimeFormatter.ofPattern("d-M-yyyy");
        LocalDate start = LocalDate.parse("1-" +input_StartMonthYear, df);
        LocalDate end   = LocalDate.parse("1-" + input_EndMonthYear, df);
        for(LocalDate d = start; d.isBefore(end.plusMonths(1)); d = d.plusMonths(1)){
            System.out.println("firstDay -> " + d.with(TemporalAdjusters.firstDayOfMonth()));
            System.out.println("lastDay -> " + d.with(TemporalAdjusters.lastDayOfMonth()));
            System.out.println();
        }
    }
}

厄立特里亚的回答很好。如果您喜欢流解决方案,这里有一个:

    DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("M-u");
    Period step = Period.ofMonths(1);
    
    String inputStartMonthYear = "1-2019";
    String inputEndMonthYear = "6-2020";

    LocalDate startDateInclusive
            = YearMonth.parse(inputStartMonthYear, monthYearFormatter).atDay(1);
    LocalDate endDateExclusive = YearMonth
            .parse(inputEndMonthYear, monthYearFormatter)
            .plusMonths(1)
            .atDay(1);
    
    startDateInclusive.datesUntil(endDateExclusive, step)
            .forEach(d1 -> {
                System.out.println("firstDay-> " + d1);
                LocalDate endOfMonth = d1.with(TemporalAdjusters.lastDayOfMonth());
                System.out.println("lastDay-> " + endOfMonth);
            });

输出有点长,所以我只给你第一行和最后一行:

firstDay-> 2019-01-01
lastDay-> 2019-01-31
firstDay-> 2019-02-01
lastDay-> 2019-02-28
firstDay-> 2019-03-01
lastDay-> 2019-03-31
firstDay-> 2019-04-01
lastDay-> 2019-04-30
(... cut ...)
firstDay-> 2020-05-01
lastDay-> 2020-05-31
firstDay-> 2020-06-01
lastDay-> 2020-06-30