Java Date and Time

It is a sunny day in the Twin Cities of Minneapolis and St. Paul.

Earlier today I read an article on Medium that described how bad are the crypto currencies and which actors are making money of it. I missed to bookmark the article. While writing this post, in an attempt to locate the article, I did a Google search using the following string: “medium crypto currency”. It returned several articles. I did not spend the time looking for it. That said; if you are investing on crypto currencies, perhaps it would be a good idea to read some of the articles that have reasons why you should stop doing so. That said, I have invested a few dollars on crypto currencies. My reasoning was to better understand what Bitcoin, among other crypto currencies is all about.

Today is the birthday of the wife of one of my wife brothers. We are invited later this afternoon. Hopefully the weather will hold. It is nice to attend a BBQ on a sunny day.

Today and for a few more days, I will attempt to solve some problems in HackerRank. In the past couple years I have concentrated on solving problems from LeetCode.

In this post I will solve the Java Date and Time. It seems that it provides you with a good refresh on how to manipulate date-time classes.

You are given a date.
You just need to write the method, getDay, which returns the day on that date.
To simplify your task, we have provided a portion of the code in the editor.

Example:

month = 8
day = 14
year = 2017

The method should return MONDAY as the day on that date.

Input Format

A single line of input containing the space separated month, day and year, respectively, in MM DD YYYY format.

Constraints

o 2000 < year < 3000

We are given a date in a specified format and we need to return the associated day. The input date is in the form of a string “MM DD YYYY” and we need to return the day of the week associated with it e.g., “TUESDAY”.

We will be solving this problem using the Java programming language and the VSCode IDE on a Windows computer. The simplest way is to solve the problem directly using the IDE provided by LeetCode.

    /*
     * Complete the 'findDay' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts following parameters:
     *  1. INTEGER month
     *  2. INTEGER day
     *  3. INTEGER year
     */

    public static String findDay(int month, int day, int year) {

    }

The signature for the function of interest takes the day, month and year and should return the associated day of the week.

08 05 2015
main <<< ==>WEDNESDAY<==
main <<< ==>WEDNESDAY<==


09 18 2021
main <<< ==>SATURDAY<==
main <<< ==>SATURDAY<==


09 19 2021
main <<< ==>SUNDAY<==
main <<< ==>SUNDAY<==

Our test code reads the provided date, extracts the day, month and year and calls the function of interest. The result is then displayed. Note that we have two separate implementations. We are only required one.

    /**
     * Test scaffold.
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        
        // **** open a buffered reader ****
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // **** read the date string ****
        String[] date = br.readLine().trim().split(" ");

        // **** close buffered reader ****
        br.close();

        // **** call function of interest and display result ****
        System.out.println("main <<< ==>" + 
            findDay(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2])) + "<==");

        // **** call function of interest and display result ****
        System.out.println("main <<< ==>" + 
            findDay1(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2])) + "<==");
    }

The test scaffold opens a buffered reader and reads the line with the input date. The line is split into three string values, one for each component of the date. We then close the buffered reader.

We then call the function of interest and pass the specified arguments. The result is displayed. The process repeats for a second implementation.

    /**
     * You are given a date.
     * You just need to write the method, getDay, which returns the day on that date.
     * To simplify your task, we have provided a portion of the code in the editor.
     */
    public static String findDay(int month, int day, int year) throws DateTimeParseException {

        // **** sanity check(s) **** 
        if (month < 1 || month > 12) return "";
        if (day < 1 || day > 31) return "";
        if (year < 2000 || year >= 3000) return "";

        // **** format the date string ****
        String dateStr = String.format("%4d-%02d-%02d", year, month, day);

        // **** generate specified date ****
        LocalDate date = LocalDate.parse(dateStr);

        // **** get the day of week from the date ****
        DayOfWeek dayOfWeekInt = date.getDayOfWeek();

        // **** return the day of the week as a string ****
        return dayOfWeekInt.toString();
    }

We start by performing some sanity checks.

We then generate a string with the matching format for the parse() function.

Once we get the associated date we extract the day of the week in binary format.

Finally we return the day of the week as a string.

    /**
     * You are given a date.
     * You just need to write the method, getDay, which returns the day on that date.
     * To simplify your task, we have provided a portion of the code in the editor.
     */
    public static String findDay1(int month, int day, int year) throws DateTimeParseException {

        // **** sanity check(s) **** 
        if (month < 1 || month > 12) return "";
        if (day < 1 || day > 31) return "";
        if (year < 2000 || year >= 3000) return "";

        // **** initialization ****
        String[] dayNames = {   "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY",
                                "FRIDAY", "SATURDAY"};

        // **** instantiate a calendar ****
        Calendar cal = Calendar.getInstance();

        // **** set the calendar for the specified date ****
        cal.set(year, month - 1, day);

        // **** get the day of the week ****
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

        // **** return the associated name of the day ****
        return dayNames[dayOfWeek - 1];
    }

In this implementation we create an array of strings with the associated names of the days of the week in upper case.

We then instantiate a calendar in which we will use to specify the input date.

The date is set.

We then get the day of the week in binary.

The function uses the array with the days of the week to return the specified string.

Note that this function has an additional line of code and used memory to build the array of strings.

Hope you enjoyed solving this problem as much as I did. The entire code for this project can be found in my GitHub repository.

Please note that the code here presented might not be the best possible solution. In most cases, after solving the problem, you can take a look at the best accepted solution provided by the different web sites (i.e., HackerRank, LeetCode).

If you have comments or questions regarding this, or any other post in this blog, please do not hesitate and leave me a note below. I will reply as soon as possible.

Keep on reading and experimenting. It is one of the best ways to learn, become proficient, refresh your knowledge and enhance your developer toolset.

Thanks for reading this post, feel free to connect with me John Canessa at LinkedIn.

Regards;

John

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.