To get the day of the week from a java.util.Date object, we can use the java.text.SimpleDateFormat
class. First, create a Date
object. Next, create a SimpleDateFormat
instance using the getDateInstance()
method, passing the String
“E” or “EEEE” as the argument. Get the day of the week as a String
using the format()
method passing in the java.util.Date
object. To get the weekday in numerical format, we can use the java.util.Calendar
object’s get method passing in Calendar.DAY_OF_WEEK
.
Get Day of Week from Date in Java – Example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// // The following example code demonstrates how to // print out the Day of the Week from a Date object. // public class GetDayFromDate { public static void main(String[] args) { Date now = new Date(); SimpleDateFormat simpleDateformat = new SimpleDateFormat("E"); // the day of the week abbreviated System.out.println(simpleDateformat.format(now)); simpleDateformat = new SimpleDateFormat("EEEE"); // the day of the week spelled out completely System.out.println(simpleDateformat.format(now)); Calendar calendar = Calendar.getInstance(); calendar.setTime(now); System.out.println(calendar.get(Calendar.DAY_OF_WEEK)); // the day of the week in numerical format } } |
Here is the output of the example code for getting the day of the week:
1 2 3 |
Wed Wednesday 4 |
Are you interested in the cutting edge of AI processors? Read how to build the Ex-Machina Wetware Brain and learn about the Knowm Technology Stack.
4 Comments