How to find day of the week when entered a date (mm/dd/yyyy) in JAVA?
In this Java tutorial, we gonna learn how to find day of a given date in Java easily. I will show you an easy example so that you can understand it easily.
HOW TO FIND DAY OF A GIVEN DATE IN JAVA
To find the day of a given number in Java, the date is given as input, we will use Calendar class, which is an abstract class that allows us to use the methods for converting between a specific instant in time and a set of calendar fields such as:
- Year
- Month
- Day of Month
- Hour
- Day of the next week and so on
If you are not familiar with classes concept you can read the following article:
Concept Of Class and Object in Java With Examples
For this, let’s take an example
The yellow highlighted date will be our input date.
Also read,
Working with ArrayList in Java ( Adding,Removing elements)
How Java objects are stored in memory
Now, if we take this as an input:
05 10 2018
Then the output for this input according to the given problem is
THURSDAY
Curious to know how to do that?
Now, let’s see the code:
//JAVA7 import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String month = in.next(); String day = in.next(); String year = in.next(); Calendar c = Calendar.getInstance(); c.set(Integer.parseInt(year), Integer.parseInt(month)-1,Integer.parseInt(day)); String dayOfWeek = getDayOfWeek(c.get(Calendar.DAY_OF_WEEK)); System.out.println(dayOfWeek.toUpperCase() ); } private static String getDayOfWeek(int value){ String day = ""; switch(value){ case 1: day="Sunday"; break; case 2: day="Monday"; break; case 3: day="Tuesday"; break; case 4: day="Wednesday"; break; case 5: day="Thursday"; break; case 6: day="Friday"; break; case 7: day="Saturday"; break; } return day; } }
Input
01 23 2018
Output
TUESDAY
I hope this tutorial was helpful to you. Feel free to comment and share.
You may also read,
in this section one problem is why month-1 it has been taken.
month – the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
Not getting Correct output in case of
input : 04 06 2012
could you please explain the code line by line ,as i am not able to understand the 16th line of code