Answer to Question #314339 in Java | JSP | JSF for superBoy

Question #314339

Write a class to represent dates (i.e., day/month/year). Add methods that should perform operations such as determining the number of days between two dates, add two dates, determining the number of months between two dates and determining the day of the week that a particular date falls on. Write a test class to confirm that your date class works.


1
Expert's answer
2022-03-19T12:25:19-0400
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import static java.lang.Math.abs;

public class CheckDate {

    public static int getDayNumberNew(LocalDate date) {
        DayOfWeek day = date.getDayOfWeek();
        return day.getValue();
    }

    public static void main(String[] args) {
        CheckDate checkDate = new CheckDate();
        Scanner in = new Scanner(System.in);
        String[] weekDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

        System.out.println("Enter date in \"dd.MM.yyyy\" format");
        String firstString = in.nextLine();
        String secondString = in.nextLine();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");

        LocalDate startDate = LocalDate.parse(firstString, formatter);
        LocalDate endDate = LocalDate.parse(secondString, formatter);
        Period period = Period.between(startDate, endDate);
        
        int days = abs(period.getDays())+abs(period.getYears())*365+abs(period.getMonths())*30;
        System.out.println("Between dates " + days + " days." );

        int months = abs(period.getMonths()) + abs(period.getYears())*12;
        System.out.println("Between dates " + months + " months." );

        System.out.println("Enter date in \"dd.MM.yyyy\" format to find out the day of the week");
        String findString = in.nextLine();
        LocalDate findDate = LocalDate.parse(findString, formatter);
        System.out.println("This day is " + weekDays[checkDate.getDayNumberNew(findDate)-1]);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS