首页 > 解决方案 > 如何在java中获取给定月份的第一个日期和最后一个日期?

问题描述

我们将以 yyyyMM 格式传递月份信息。从给定的输入中,我将如何获得该月的 FirstDate 和 LastDate?

Input:-202002

OutPut Should be:-

First Date:- 2020-02-01,
Last Date:- 2020-02-29

DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
Date date = new Date();
System.out.println("First Date:- "+dateFormat.format(date));    
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
Date previousmonth = calendar.getTime();
System.out.println("LastDate:-"+dateFormat.format(previousmonth).toString());

标签: javajava.util.datejava.util.calendar

解决方案


正如我刚刚了解到的,现在有一些特殊的方法。

你现在可以这样做:

public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMM");
public static final DateTimeFormatter OUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

public static LocalDate[] getFirstAndLastDateOfMonthNew(String yearAndMonth) {
    final LocalDate[] result = new LocalDate[2];
    final YearMonth yearMonth = YearMonth.parse(yearAndMonth, FORMATTER);
    result[0] = yearMonth.atDay(1);
    result[1] = yearMonth.atEndOfMonth();;
    return result;
}

旧的方法是:

只需将其添加01到日期并解析它。加一个月减一天。

public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
public static final DateTimeFormatter OUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

public static LocalDate[] getFirstAndLastDateOfMonth(String yearAndMonth) {
    final LocalDate[] result = new LocalDate[2];
    final LocalDate first = LocalDate.parse(yearAndMonth + "01", FORMATTER);
    final LocalDate last = first.plusMonths(1).minusDays(1);
    result[0] = first;
    result[1] = last;
    return result;
}

推荐阅读