首页 > 解决方案 > 如何编写一个返回过去月份和年份的第一天和最后一天的方法?

问题描述

该类dateTimeInherit是继承自的类,dateTimeAbstract因此它必须使用该daysOfAnyMonth方法。我正在考虑使用YearMonthandLocalDate类中的一些类,但不知道从那里去哪里。

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
}

标签: javadateinheritancecalendar

解决方案


我绝对同意你使用YearMonthLocalDatefrom java.time,现代 Java 日期和时间 API。

将您的月份编号和年份传递给YearMonth.of(int, int). 有关文档,请参阅下面的链接。记住交换论点:年份优先。将获取的YearMonth对象存储到变量中。使用它的atDayatEndOfMonth方法获取当月的第一天和最后一天作为LocalDate对象。反过来LocalDate.getDayOfWeek()用于获取星期几。

链接


推荐阅读