1

PHP has a built-in function that takes a data and returns the day of the week it is (Monday, Tuesday, etc.). Does Java have a similar function?

zmol
  • 2,834
  • 5
  • 26
  • 29
  • Modern solution uses `java.time.LocalDate` and the `DayOfWeek` enum. Ex: `LocalDate.now().getDayOfWeek().getDisplayName( … )` – Basil Bourque Oct 01 '18 at 00:44

4 Answers4

5

Old style(pretty old..)

import java.util.*;

public class GetDay {
    public static void main(String[] args) {
        Calendar calendar = new GregorianCalendar();
        calendar.set(2011, 1, 9); // 1 = Feb  months are zero based remember
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK));  
    }
}

In java-8 it could be as simple as

LocalDate.now().getDayOfWeek //get day of week for current day
LocalDate.of(2016, 01, 01).getDayOfWeek //get day of week for a particular day

This call return a DayOfWeek enum value which in itself has some nice functions.

ayush
  • 14,350
  • 11
  • 53
  • 100
  • FYI, the terribly troublesome old date-time classes such as `java.util.Date`, [`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). Ex: `LocalDate.now().getDayOfWeek().getDisplayName( … )` – Basil Bourque Oct 01 '18 at 00:43
4

Yes Calendar.DAY_OF_WEEK

Calendar c=Calendar.getInstance();
switch (c.get(Calendar.DAY_OF_WEEK))
{
   case Calendar.MONDAY: ...;
   case Calendar.TUESDAY: ...;
}
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
4
java.util.Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

You can use the Calendar class:

Example:

Calendar newCal = new GregorianCalendar();
newCal.set(1997, 2, 1, 0, 0, 0);
newCal.setTime(newCal.getTime());    
int day = newCal.get(Calendar.DAY_OF_WEEK);

Reference:

http://www.java-tips.org/java-se-tips/java.util/determine-the-day-of-the-week.html

optimistAk
  • 359
  • 1
  • 4