java - 如何在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());
解决方案
正如我刚刚了解到的,现在有一些特殊的方法。
你现在可以这样做:
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;
}
推荐阅读
- javascript - 在 .then() 链中间重试 fetch() 调用
- python - Python 在 x 轴上绘制多年数据的日期时间
- python - 使用 sympy 求解具有初始条件的微分方程并获得隐式结果
- c# - 无法将类型“string”隐式转换为“int”(C#)
- r - 添加一个变量以指定几个变量中的哪一个等于一个值
- python - 如何将包含嵌套列表的数组值的字典转换为 pandas 数据框?
- json - Pentaho Kettle:如何动态获取 JSON 文件列
- flutter - 如何在飞镖和颤振中计数并获取指定值的列表
- javascript - 使用anime.js在html中做序列动画
- arrays - Laravel 查询多个数组