Brian McCanaugh
Brian McCanaugh

Reputation: 165

Getting day of week from a string data with simple date format in java

I am trying to get the day of week from an arraylist that contains String of date in the simple format ("yyyy-MM-dd"). For example, I have the arraylist = {"2021-04-01", "2021-05-03", "2020-06-17"}. Is it possible to determine what day of week belong to each of these dates? So for the first String of "2021-04-01", I would like to turn it into "Thursday".

Thank you for your help!

Upvotes: 0

Views: 853

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 78995

Your date strings conform to the ISO 8601 standards. The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.

Simply parse the strings using LocalDate#parse and use LocalDate#getDayOfWeek to get the day of the week e.g.

System.out.println(
    LocalDate.parse("2021-04-01")
             .getDayOfWeek()
             .getDisplayName(TextStyle.FULL, Locale.ENGLISH)
);

Demo with some more styles:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        Stream.of(
                "2021-04-01", 
                "2021-05-03", 
                "2020-06-17"
        ).forEach(s -> 
            System.out.printf(
                "%s, %s, %s%n", 
                LocalDate.parse(s).getDayOfWeek(),
                LocalDate.parse(s).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH),
                LocalDate.parse(s).getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.ENGLISH)
            )
        );
        
        System.out.println("+-+-+-+-+-+-+-+-+-+-+-+-+");
        
        // Non-Stream solution:
        // Also, showing only one style without using String#format i.e. %s
        List<String> strDateList = Arrays.asList(
                                        "2021-04-01", 
                                        "2021-05-03", 
                                        "2020-06-17"
                                    );
        
        for(String s: strDateList) {
            LocalDate date = LocalDate.parse(s);
            DayOfWeek dow = date.getDayOfWeek();
            System.out.println(dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH));
        }
    }
}

Output:

THURSDAY, Thursday, Thu
MONDAY, Monday, Mon
WEDNESDAY, Wednesday, Wed
+-+-+-+-+-+-+-+-+-+-+-+-+
Thursday
Monday
Wednesday

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Upvotes: 4

Related Questions