31

If I have int year, int month, int day in Java, how to find name of day ? Is there already some functions for this ?

Ivana
  • 319
  • 1
  • 3
  • 3
  • 2
    If you have found your answer you should accept the answer that helped you the most. – RMT Jul 22 '11 at 14:45
  • Modern solution uses `java.time.LocalDate` and the `DayOfWeek` enum. Ex: `LocalDate.of( y , m , d ).getDayOfWeek().getDisplayName( … )` – Basil Bourque Oct 01 '18 at 00:49
  • LocalDate.of(year,month,day).getDayOfWeek().toString();works well in java 8 don't forget to import java.util.*; – Ravi Mar 13 '19 at 17:04

9 Answers9

50

Use SimpleDateFormat with a pattern of EEEE to get the name of the day of week.

// Assuming that you already have this.
int year = 2011;
int month = 7;
int day = 22;

// First convert to Date. This is one of the many ways.
String dateString = String.format("%d-%d-%d", year, month, day);
Date date = new SimpleDateFormat("yyyy-M-d").parse(dateString);

// Then get the day of week from the Date based on specific locale.
String dayOfWeek = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);

System.out.println(dayOfWeek); // Friday

Here it is wrapped all up into a nice Java class for you.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


public class DateUtility
{

    public static void main(String args[]){
        System.out.println(dayName("2015-03-05 00:00:00", "YYYY-MM-DD HH:MM:ss"));
    }

    public static String dayName(String inputDate, String format){
        Date date = null;
        try {
            date = new SimpleDateFormat(format).parse(inputDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);
    }
}
Dan Ciborowski - MSFT
  • 6,807
  • 10
  • 53
  • 88
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    Should be the accepted answer! Dont forget to `import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;` – Dan Ciborowski - MSFT Jun 18 '16 at 09:24
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 28 '18 at 05:40
16

You can do something like this to get the names of the days of the week for different locales.

Here's the important part:

DateFormatSymbols dfs = new DateFormatSymbols(usersLocale);
String weekdays[] = dfs.getWeekdays();

That can be combined with this:

Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_WEEK);

To get what you're looking for:

String nameOfDay = weekdays[day];
alexcoco
  • 6,657
  • 6
  • 27
  • 39
10

You can use the Calendar Object to find this.

Once you create the calendar instance you get the DAY_OF_WEEK (which is an int) then you can find the day from there)

You can use a switch statement like so:

import java.util.*;

public class DayOfWeek {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DAY_OF_WEEK);
        System.out.print("Today is ");
        switch (day) {
            case 1:
                System.out.print("Sunday");
                break;
            case 2:
                System.out.print("Monday");
                break;
            case 3:
                System.out.print("Tuesday");
                break;
            case 4:
                System.out.print("Wednesday");
                break;
            case 5:
                System.out.print("Thursday");
                break;
            case 6:
                System.out.print("Friday");
                break;
            case 7:
                System.out.print("Saturday");
        }
        System.out.print(".");
    }
}
HendraWD
  • 2,984
  • 2
  • 31
  • 45
RMT
  • 7,040
  • 4
  • 25
  • 37
  • and that will give you an int, not a name – Bozho Jul 22 '11 at 11:43
  • that's English-only. What about German? – Bozho Jul 22 '11 at 11:53
  • @Bozho, well you can change the language, or you can internationalize it, so it will pick up the locale and set it to what ever you language you prefer – RMT Jul 22 '11 at 11:55
  • That's just an example. The user can use whatever Strings they want to represent this. For an example that depends on locale, see my answer. – alexcoco Jul 22 '11 at 11:56
  • 1
    my point exactly - you should use what is given by the jvm rather than writing your own. – Bozho Jul 22 '11 at 11:57
  • use the constants `Calendar.SUNDAY`, `Calendar.MONDAY`, ... instead of the direct values. Better use `DateFormatSymbols.getWeekdays()` to retrieve the localized names. – user85421 Jul 22 '11 at 12:04
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 28 '18 at 05:40
  • Instead, let [`DayOfWeek.getDisplayName`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/DayOfWeek.html#getDisplayName(java.time.format.TextStyle,java.util.Locale)) automatically localize the day-of-week name. It is a one-liner: `java.time.LocalDate.now().getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.US )` …or `Locale.CANADA_FRENCH` etc. – Basil Bourque Dec 28 '18 at 05:41
10

Construct a GregorianCalendar with the year, month and day, then query it to find the name of the day. Something like this:

int year = 1977;
int month = 2;
int dayOfMonth = 15;
Calendar myCalendar = new GregorianCalendar(year, month, dayOfMonth);

int dayOfWeek = myCalendar.get(Calendar.DAY_OF_WEEK);

Note that the day of week is returned as an int representing the ordinal of the day in the locale's week day representation. IE, in a locale where the weekday starts on Monday and ends on Sunday, a 2 would represent Tuesday, whereas if the locale weekday starts on Sunday then that same 2 would represent Monday.

Edit

And since there is alot of answer editing going on, allow me to add the following:

DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
String dayOfMonthStr = symbols.getWeekdays()[dayOfMonth];

Thought to be honest, I like the SimpleDateFormatter approach better, because it encapsulates the very same code as I've shown above. Silly me to forget all about it.

Perception
  • 79,279
  • 19
  • 185
  • 195
  • 2
    caution: month is zero-based, that will be a March 15th! (not February) – user85421 Jul 22 '11 at 11:58
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Oct 01 '18 at 00:49
9

The name of the week day differs per locale. So you have to use a DateFormat with the proper locale. For example:

SimpleDateFormat format = new SimpleDateFormat("EEEE");
System.out.println(format.format(date));

The Date object can be obtained in multiple ways, including the deprecated Date(..) constructor, the Calendar.set(..) methods or joda-time DateTime. (for the latter you can use joda-time's own DateTimeFormat)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
4
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 22); //Set Day of the Month, 1..31
cal.set(Calendar.MONTH,6); //Set month, starts with JANUARY = 0
cal.set(Calendar.YEAR,2011); //Set year
System.out.println(cal.get(Calendar.DAY_OF_WEEK)); //Starts with Sunday, 6 = friday
ruhsuzbaykus
  • 13,240
  • 2
  • 20
  • 21
3

This kind of date-time work is easier when using the Joda-Time library. A simple one-liner.

String dayOfWeek = new LocalDate( 2014, 1, 2 ).dayOfWeek().getAsText( java.util.Locale.ENGLISH );

System.out.println( "dayOfWeek: " + dayOfWeek );

When run…

dayOfWeek: Thursday
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1
new GregorianCalendar().setTime(new Date()).get(DAY_OF_WEEK)

That gives you a number, Calendar.SUNDAY == 1, Calendar.MONDAY == 2, ...

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
1

Yes, but it's a rather long process with the JDK. JodaTime may be a better choice (I haven't used it).

First, you get a Calendar object, so that you can construct a date from day/month/year/timezone. Do not use one of the deprecated Date constructors.

Then get a Date object from that calendar, and pass it to SimpleDateFormat. Note that the format objects are not threadsafe.

  // by default, this Calendar object will have the current timezone
  Calendar cal = GregorianCalendar.getInstance();
  cal.set(2011, 6, 22);

  // this formatter will have the current locale
  SimpleDateFormat format = new SimpleDateFormat("EEEE");

  System.out.println(format.format(cal.getTime()));
parsifal
  • 1,507
  • 8
  • 7