java - 如何编写一个返回过去月份和年份的第一天和最后一天的方法?
问题描述
该类dateTimeInherit
是继承自的类,dateTimeAbstract
因此它必须使用该daysOfAnyMonth
方法。我正在考虑使用YearMonth
andLocalDate
类中的一些类,但不知道从那里去哪里。
import java.io.IOException;
public class Driver
{
public static void main(String[] args) throws IOException
{
DateTimeInherit dateTimeInherit = new DateTimeInherit();
/**
* From the given line of codes you have to identify the class name and necessary
constructors/methods
* In the following method, the first parameter is the month and the second parameter is the
year.
* We are going to print the first day and the last day (day of the week) of any given month of
the year.
* Output format: for (4, 2020):
* In the year 2020, for the 4th month: the first day is WEDNESDAY and the last day is
THURSDAY
*/
dateTimeInherit.daysOfAnyMonth(9, 2020);
dateTimeInherit.daysOfAnyMonth(10, 2020);
dateTimeInherit.daysOfAnyMonth(12, 2020);
System.out.print("\n");
public abstract class DateTimeAbstract
{
abstract void daysOfAnyMonth(int monthOfYear, int theYear);
}
import java.util.Calendar;
public class DateTimeInherit extends DateTimeAbstract
{
// Method that needs to be written
}
解决方案
我绝对同意你使用YearMonth
和LocalDate
from java.time,现代 Java 日期和时间 API。
将您的月份编号和年份传递给YearMonth.of(int, int)
. 有关文档,请参阅下面的链接。记住交换论点:年份优先。将获取的YearMonth
对象存储到变量中。使用它的atDay
和atEndOfMonth
方法获取当月的第一天和最后一天作为LocalDate
对象。反过来LocalDate.getDayOfWeek()
用于获取星期几。
链接
推荐阅读
- r - 单独的正则表达式混淆
- javascript - 如何按对象属性值对对象数组进行分组?
- c++ - QSqlTablelModel 找不到 SQL 视图,但 QSqlQuery 可以
- graylog - 使用正则表达式来保存带有 HTTP 响应 4** 和 5** 的访问日志
- rest - 如果后端不允许重复,POST 方法是否是幂等的?
- django - 与贝宝重定向问题的集成
- php - 如何为laravel本地存储生成临时文件下载url?
- flutter - 如何从测试中访问 Flutter 环境变量?
- android - 如何从 Kotlin 中的设置活动中检索首选项?
- reactjs - 有没有办法显示安全和执行的图像?