Find Day of Week using SimpleDateFormat class in Java

Given the day, month, and year, the task is to find the corresponding day of the week using SimpleDateFormat class in Java.
Examples
Input: 11-08-2020
Output: Tuesday
Explanation: The day corresponding to the date 11-08-2020 is tuesday.
Input: 17-08-2006
Output: Thursday
Explanation: The day corresponding to the date 17-08-2006 is thursday.
Approach:
- Input the date, month, and year from the user as integer type.
- Check if the date, month, and year are in the required range. If not, raise an error message.
- Convert the input into Date type using SimpleDateFormat class.
- Format the date to the corresponding day of the week using SimpleDateFormat class.
- Print the corresponding day of the week.
Note: If you want the full name of the day (ex: Sunday, Monday), use “EEEE”. If you want the shorter version of the name of the day (ex: Sun, Mon), use “EE”.
Below is the implementation of the above approach:
Java
// Java program for the above approachimport java.util.Date;import java.text.SimpleDateFormat;import java.text.ParseException; public class GFG { public void findDay(int day, int month, int year) { String dayOfWeek = ""; boolean wrongDate = false; if (day < 1 || day > 31) { dayOfWeek += "Give day in range. "; wrongDate = true; } if (month < 1 || month > 12) { dayOfWeek += "Give month in range. "; wrongDate = true; } if (year <= 0) { wrongDate = true; dayOfWeek += "Give year in range."; } if (!wrongDate) { SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); String dateString = day + "-" + month + "-" + year; try { // Parse the String representation of date // to Date Date date = dateFormatter.parse(dateString); dayOfWeek = "Day of week on " + dateString + " : " + new SimpleDateFormat("EEEE").format( date); } catch (ParseException e) { e.printStackTrace(); } } System.out.println(dayOfWeek); } // Driver Code public static void main(String arg[]) { GFG gfg = new GFG(); gfg.findDay(17, 8, 2006); }} |
Output
Day of week on 17-8-2006 : Thursday



