gpt4 book ai didi

java - 如何在java中获取给定月份的第一个日期和最后一个日期?

转载 作者:行者123 更新时间:2023-12-01 19:29:09 25 4
gpt4 key购买 nike

我们将以 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());

最佳答案

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

你现在可以这样做:

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;
}

关于java - 如何在java中获取给定月份的第一个日期和最后一个日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60317515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com