Did this blog help you solve a problem? Tip me with Bitcoins at: 17dQktcAmU4urXz7tGk2sbuiCqykm3WLs6

Thursday, May 5, 2011

Get Day of Week from Date Object in Java

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

// 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

        simpleDateformat = new SimpleDateFormat("EEEE"); // the day of the week spelled out completely

        Calendar calendar = Calendar.getInstance();
        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:


Anonymous said...

This is wrong... "dd" gives you the day in the month. When you wrote this it worked b/c it was still the first week of the month.

Tim Molter said...

@ Anonymous Thanks for pointing that out. I fixed it.