228

For Example I have the date: "23/2/2010" (23th Feb 2010). I want to pass it to a function which would return the day of week. How can I do this?

In this example, the function should return String "Tue".

Additionally, if just the day ordinal is desired, how can that be retrieved?

Lakshya Goyal
  • 360
  • 1
  • 6
  • 24
evilReiko
  • 19,501
  • 24
  • 86
  • 102
  • 2
    If you're reading this, please skip ahead/down to the answers using the current methodology of java.time! The Calendar-based answers are fine, but outdated now. – Brian Agnew Oct 08 '21 at 09:50

29 Answers29

403

Yes. Depending on your exact case:

  • You can use java.util.Calendar:

    Calendar c = Calendar.getInstance();
    c.setTime(yourDate);
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    
  • if you need the output to be Tue rather than 3 (Days of week are indexed starting at 1 for Sunday, see Calendar.SUNDAY), instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")

  • if you have your input as string, rather than Date, you should use SimpleDateFormat to parse it: new SimpleDateFormat("dd/M/yyyy").parse(dateString)

  • you can use joda-time's DateTime and call dateTime.dayOfWeek() and/or DateTimeFormat.

  • edit: since Java 8 you can now use java.time package instead of joda-time

pdem
  • 3,880
  • 1
  • 24
  • 38
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 26
    Days of week start from 1 which is Sunday, so I think Tue would be 3. – Mohammad Banisaeid Aug 07 '13 at 12:03
  • 15
    In other things to be careful of, if you set the date in the Calendar object using integers (not via parsing a string), then be aware that the month number is zero-based, so January is 0 and December is 11. – RenniePet Aug 17 '13 at 19:46
  • 4
    @RenniePet: Good one. Also you can use constants in `Calendar` class, such as `Calendar.SUNDAY` or `Calendar.JANUARY`. – Mohammad Banisaeid Aug 18 '13 at 10:01
  • 4
    This answer was a great answer when it was written. Today you will want to the now outdated classes `Calendar`, `Date` and `DateTimeFormat` (and Joda time too) and use the Java 8 `java.time` classes, for instance `YearMonth` or `LocalDate`. See more in [this answer](http://stackoverflow.com/a/33895008/5772882). – Ole V.V. Feb 10 '17 at 19:43
  • 4
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/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/8/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Nov 03 '17 at 21:25
  • 1
    The *Joda-Time* project is in maintenance mode. The project team advises migration to the *java.time* classes. – Basil Bourque Dec 24 '17 at 17:26
  • FYI, now a one-liner using *java.time*: `LocalDate.parse( "23/2/2010" , DateTimeFormatter.ofPattern( "d/M/uuuu" ) ).getDayOfWeek().getDisplayName( TextStyle.SHORT , Locale.US )` See modern solution in [Answer by Przemek](https://stackoverflow.com/a/33895008/642706). – Basil Bourque Dec 28 '18 at 05:50
  • Is week days are 1 = Monday ,2 = Tuesday .... 7 = Sunday in SimpleDateFormat class whereas week days returned by get(Calendar.DAY_OF_WEEK) is 1 = Sunday, 2 = Monday?? Because when I format the returned day of week then for value 4 it gives Thrusday instead of Wednesday for the date 05/08/2015 (dd/MM/yyyy). – Animesh Jaiswal Sep 15 '19 at 03:47
79
  String inputDate = "01/08/2012";
  SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
  Date dt1 = format1.parse(input_date);
  DateFormat format2 = new SimpleDateFormat("EEEE"); 
  String finalDay = format2.format(dt1);

Use this code for find the day name from a input date.Simple and well tested.

Lii
  • 11,553
  • 8
  • 64
  • 88
JDGuide
  • 6,239
  • 12
  • 46
  • 64
  • 1
    If you use this method, take careful note of the order of days and months. – Joel Christophel Feb 02 '13 at 22:36
  • 1
    I think you need to put it in a try catch block – Shafaet Aug 01 '16 at 08:36
  • 3
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/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/8/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 24 '17 at 17:27
  • Android only implements LocalDate after API 26. – Jacob Sánchez Sep 22 '19 at 01:06
36

Simply use SimpleDateFormat.

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", java.util.Locale.ENGLISH);
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("EEE, d MMM yyyy");
String sMyDate = sdf.format(myDate);

The result is: Sat, 28 Dec 2013

The default constructor is taking "the default" Locale, so be careful using it when you need a specific pattern.

public SimpleDateFormat(String pattern) {
    this(pattern, Locale.getDefault(Locale.Category.FORMAT));
}
Nikolay Hristov
  • 1,602
  • 1
  • 15
  • 22
26

tl;dr

Using java.time

LocalDate.parse(                               // Generate `LocalDate` object from String input.
             "23/2/2010" ,
             DateTimeFormatter.ofPattern( "d/M/uuuu" ) 
         )                                    
         .getDayOfWeek()                       // Get `DayOfWeek` enum object.
         .getDisplayName(                      // Localize. Generate a String to represent this day-of-week.
             TextStyle.SHORT_STANDALONE ,      // How long or abbreviated. Some languages have an alternate spelling for "standalone" use (not so in English).
             Locale.US                         // Or Locale.CANADA_FRENCH and such. Specify a `Locale` to determine (1) human language for translation, and (2) cultural norms for abbreviation, punctuation, etc.
         ) 

Tue

See this code run live at IdeOne.com (but only Locale.US works there).

java.time

See my example code above, and see the correct Answer for java.time by Przemek.

Ordinal number

if just the day ordinal is desired, how can that be retrieved?

For ordinal number, consider passing around the DayOfWeek enum object instead such as DayOfWeek.TUESDAY. Keep in mind that a DayOfWeek is a smart object, not just a string or mere integer number. Using those enum objects makes your code more self-documenting, ensures valid values, and provides type-safety.

But if you insist, ask DayOfWeek for a number. You get 1-7 for Monday-Sunday per the ISO 8601 standard.

int ordinal = myLocalDate.getDayOfWeek().getValue() ;

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migrating to the java.time classes. The java.time framework is built into Java 8 (as well as back-ported to Java 6 & 7 and further adapted to Android).

Here is example code using the Joda-Time library version 2.4, as mentioned in the accepted answer by Bozho. Joda-Time is far superior to the java.util.Date/.Calendar classes bundled with Java.

LocalDate

Joda-Time offers the LocalDate class to represent a date-only without any time-of-day or time zone. Just what this Question calls for. The old java.util.Date/.Calendar classes bundled with Java lack this concept.

Parse

Parse the string into a date value.

String input = "23/2/2010";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( input );

Extract

Extract from the date value the day of week number and name.

int dayOfWeek = localDate.getDayOfWeek(); // Follows ISO 8601 standard, where Monday = 1, Sunday = 7.
Locale locale = Locale.US;  // Locale specifies the human language to use in determining day-of-week name (Tuesday in English versus Mardi in French).
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "E" ).withLocale( locale );
String output = formatterOutput.print( localDate ); // 'E' is code for abbreviation of day-of-week name. See Joda-Time doc.
String outputQuébécois = formatterOutput.withLocale( Locale.CANADA_FRENCH ).print( localDate );

Dump

Dump to console.

System.out.println( "input: " + input );
System.out.println( "localDate: " + localDate ); // Defaults to ISO 8601 formatted strings.
System.out.println( "dayOfWeek: " + dayOfWeek );
System.out.println( "output: " + output );
System.out.println( "outputQuébécois: " + outputQuébécois );

Run

When run.

input: 23/2/2010
localDate: 2010-02-23
dayOfWeek: 2
output: Tue
outputQuébécois: mar.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
24

java.time

Using java.time framework built into Java 8 and later.

The DayOfWeek enum can generate a String of the day’s name automatically localized to the human language and cultural norms of a Locale. Specify a TextStyle to indicate you want long form or abbreviated name.

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
import java.util.Locale
import java.time.DayOfWeek;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");
LocalDate date = LocalDate.parse("23/2/2010", formatter); // LocalDate = 2010-02-23
DayOfWeek dow = date.getDayOfWeek();  // Extracts a `DayOfWeek` enum object.
String output = dow.getDisplayName(TextStyle.SHORT, Locale.US); // String = Tue
nandipati vamsi
  • 363
  • 1
  • 3
  • 8
Przemek
  • 7,111
  • 3
  • 43
  • 52
  • 1
    This can be used only in Oreo and above apis. – codepeaker Nov 07 '18 at 11:08
  • 2
    @codepeaker Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Dec 28 '18 at 05:46
18

For Java 8 or Later, Localdate is preferable

import java.time.LocalDate;

public static String findDay(int month, int day, int year) {

    LocalDate localDate = LocalDate.of(year, month, day);

    java.time.DayOfWeek dayOfWeek = localDate.getDayOfWeek();
    System.out.println(dayOfWeek);

    return dayOfWeek.toString();
}

Note : if input is String/User defined, then you should parse it into int.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mimu Saha Tishan
  • 2,402
  • 1
  • 21
  • 40
10

You can try the following code:

import java.time.*;

public class Test{
   public static void main(String[] args) {
      DayOfWeek dow = LocalDate.of(2010,Month.FEBRUARY,23).getDayOfWeek();
      String s = String.valueOf(dow);
      System.out.println(String.format("%.3s",s));
   }
}
Tony Babarino
  • 3,355
  • 4
  • 32
  • 44
SHB
  • 585
  • 6
  • 14
  • How does this answer add value beyond that of the two or three prior answers using `LocalDate`? Did you read those before posting? – Basil Bourque Jun 24 '16 at 01:33
  • 1
    This is a good answer, and it IS different from all previous ones. It uses LocalDate.of() API to construct date, and it is much shorter than most other answers (sometimes short answer is better than long)... – Alexey Aug 02 '16 at 02:26
9
public class TryDateFormats {
    public static void main(String[] args) throws ParseException {
        String month = "08";
        String day = "05";
        String year = "2015";
        String inputDateStr = String.format("%s/%s/%s", day, month, year);
        Date inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);
        String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
        System.out.println(dayOfWeek);
    }
}
hitesh
  • 91
  • 1
  • 2
  • nice solution, I was finding exact this type of solution, My required line that solved my problem. String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase(); – Muhammad Azam Oct 21 '19 at 07:53
6
...
import java.time.LocalDate;
...
//String month = in.next();
int mm = in.nextInt();
//String day = in.next();
int dd = in.nextInt();
//String year = in.next();
int yy = in.nextInt();
in.close();
LocalDate dt = LocalDate.of(yy, mm, dd);
System.out.print(dt.getDayOfWeek());
5

Another "fun" way is to use Doomsday algorithm. It's a way longer method but it's also faster if you don't need to create a Calendar object with a given date.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 *
 * @author alain.janinmanificat
 */
public class Doomsday {

    public static HashMap<Integer, ArrayList<Integer>> anchorDaysMap = new HashMap<>();
    public static HashMap<Integer, Integer> doomsdayDate = new HashMap<>();
    public static String weekdays[] = new DateFormatSymbols(Locale.FRENCH).getWeekdays();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ParseException, ParseException {

        // Map is fed manually but we can use this to calculate it : http://en.wikipedia.org/wiki/Doomsday_rule#Finding_a_century.27s_anchor_day
        anchorDaysMap.put(Integer.valueOf(0), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1700));
                add(Integer.valueOf(2100));
                add(Integer.valueOf(2500));
            }
        });

        anchorDaysMap.put(Integer.valueOf(2), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1600));
                add(Integer.valueOf(2000));
                add(Integer.valueOf(2400));
            }
        });

        anchorDaysMap.put(Integer.valueOf(3), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1500));
                add(Integer.valueOf(1900));
                add(Integer.valueOf(2300));
            }
        });

        anchorDaysMap.put(Integer.valueOf(5), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1800));
                add(Integer.valueOf(2200));
                add(Integer.valueOf(2600));
            }
        });

        //Some reference date that always land on Doomsday
        doomsdayDate.put(Integer.valueOf(1), Integer.valueOf(3));
        doomsdayDate.put(Integer.valueOf(2), Integer.valueOf(14));
        doomsdayDate.put(Integer.valueOf(3), Integer.valueOf(14));
        doomsdayDate.put(Integer.valueOf(4), Integer.valueOf(4));
        doomsdayDate.put(Integer.valueOf(5), Integer.valueOf(9));
        doomsdayDate.put(Integer.valueOf(6), Integer.valueOf(6));
        doomsdayDate.put(Integer.valueOf(7), Integer.valueOf(4));
        doomsdayDate.put(Integer.valueOf(8), Integer.valueOf(8));
        doomsdayDate.put(Integer.valueOf(9), Integer.valueOf(5));
        doomsdayDate.put(Integer.valueOf(10), Integer.valueOf(10));
        doomsdayDate.put(Integer.valueOf(11), Integer.valueOf(7));
        doomsdayDate.put(Integer.valueOf(12), Integer.valueOf(12));

        long time = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {

            //Get a random date
            int year = 1583 + new Random().nextInt(500);
            int month = 1 + new Random().nextInt(12);
            int day = 1 + new Random().nextInt(7);

            //Get anchor day and DoomsDay for current date
            int twoDigitsYear = (year % 100);
            int century = year - twoDigitsYear;
            int adForCentury = getADCentury(century);
            int dd = ((int) twoDigitsYear / 12) + twoDigitsYear % 12 + (int) ((twoDigitsYear % 12) / 4);

            //Get the gap between current date and a reference DoomsDay date
            int referenceDay = doomsdayDate.get(month);
            int gap = (day - referenceDay) % 7;

            int result = (gap + adForCentury + dd) % 7;

            if(result<0){
                result*=-1;
            }
            String dayDate= weekdays[(result + 1) % 8];
            //System.out.println("day:" + dayDate);
        }
        System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 80

         time = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            Calendar c = Calendar.getInstance();
            //I should have used random date here too, but it's already slower this way
            c.setTime(new SimpleDateFormat("dd/MM/yyyy").parse("12/04/1861"));
//            System.out.println(new SimpleDateFormat("EE").format(c.getTime()));
            int result2 = c.get(Calendar.DAY_OF_WEEK);
//            System.out.println("day idx :"+ result2);
        }
        System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 884
    }

    public static int getADCentury(int century) {
        for (Map.Entry<Integer, ArrayList<Integer>> entry : anchorDaysMap.entrySet()) {
            if (entry.getValue().contains(Integer.valueOf(century))) {
                return entry.getKey();
            }
        }
        return 0;
    }
}
alain.janinm
  • 19,951
  • 10
  • 65
  • 112
5

Can use the following code snippet for input like (day = "08", month = "05", year = "2015" and output will be "WEDNESDAY")

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
calendar.set(Calendar.MONTH, (Integer.parseInt(month)-1));
calendar.set(Calendar.YEAR, Integer.parseInt(year));
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
rab
  • 207
  • 2
  • 6
3
private String getDay(Date date){

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
    //System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());                       
    return simpleDateFormat.format(date).toUpperCase();
}

private String getDay(String dateStr){
    //dateStr must be in DD-MM-YYYY Formate
    Date date = null;
    String day=null;

    try {
        date = new SimpleDateFormat("DD-MM-YYYY").parse(dateStr);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
        //System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
        day = simpleDateFormat.format(date).toUpperCase();


    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    return day;
}
Az.MaYo
  • 1,044
  • 10
  • 23
3

Program to find the day of the week by giving user input date month and year using java.util.scanner package:

import java.util.Scanner;

public class Calender {
    public static String getDay(String day, String month, String year) {

        int ym, yp, d, ay, a = 0;
        int by = 20;
        int[] y = new int[]{6, 4, 2, 0};
        int[] m = new int []{0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};

        String[] wd = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

        int gd = Integer.parseInt(day);
        int gm = Integer.parseInt(month);
        int gy = Integer.parseInt(year);

        ym = gy % 100;
        yp = ym / 4;
        ay = gy / 100;

        while (ay != by) {
            by = by + 1;
            a = a + 1;

            if(a == 4) {
                a = 0;
            }
        }

        if ((ym % 4 == 0) && (gm == 2)) {
            d = (gd + m[gm - 1] + ym + yp + y[a] - 1) % 7;
        } else
            d = (gd + m[gm - 1] + ym + yp + y[a]) % 7;

        return wd[d];
    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        String day = in.next();
        String month = in.next();
        String year = in.next();

        System.out.println(getDay(day, month, year));
    }
}
Pochmurnik
  • 780
  • 6
  • 18
  • 35
Noone
  • 31
  • 1
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/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/8/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Nov 03 '17 at 21:25
  • 1
    @Dave is this really nice to read? `if ((ym%4==0) && (gm==2)){ d=(gd+m[gm-1]+ym+yp+y[a]-1)%7;` – Pochmurnik Mar 06 '19 at 09:05
3

One line answer:

return LocalDate.parse("06/02/2018",DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();

Usage Example:

public static String getDayOfWeek(String date){
  return LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();
}

public static void callerMethod(){
   System.out.println(getDayOfWeek("06/02/2018")); //TUESDAY
}
Sahil Chhabra
  • 10,621
  • 4
  • 63
  • 62
3
import java.time.*;

public static String findDay(int month, int day, int year) {
    LocalDate localDate = LocalDate.of(year, month, day);
    DayOfWeek dayOfWeek = localDate.getDayOfWeek();
    return dayOfWeek.name();
}
Jatin
  • 91
  • 5
2
import java.text.SimpleDateFormat;
import java.util.Scanner;

class DayFromDate {

    public static void main(String args[]) {

        System.out.println("Enter the date(dd/mm/yyyy):");
        Scanner scan = new Scanner(System.in);
        String Date = scan.nextLine();

        try {
            boolean dateValid = dateValidate(Date);

            if(dateValid == true) {
                SimpleDateFormat df = new SimpleDateFormat( "dd/MM/yy" );  
                java.util.Date date = df.parse( Date );   
                df.applyPattern( "EEE" );  
                String day= df.format( date ); 

                if(day.compareTo("Sat") == 0 || day.compareTo("Sun") == 0) {
                    System.out.println(day + ": Weekend");
                } else {
                    System.out.println(day + ": Weekday");
                }
            } else {
                System.out.println("Invalid Date!!!");
            }
        } catch(Exception e) {
            System.out.println("Invalid Date Formats!!!");
        }
     }

    static public boolean dateValidate(String d) {

        String dateArray[] = d.split("/");
        int day = Integer.parseInt(dateArray[0]);
        int month = Integer.parseInt(dateArray[1]);
        int year = Integer.parseInt(dateArray[2]);
        System.out.print(day + "\n" + month + "\n" + year + "\n");
        boolean leapYear = false;

        if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
            leapYear = true;
        }

        if(year > 2099 || year < 1900)
            return false;

        if(month < 13) {
            if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
                if(day > 31)
                    return false;
            } else if(month == 4 || month == 6 || month == 9 || month == 11) {
                if(day > 30)
                    return false;
            } else if(leapYear == true && month == 2) {
                if(day > 29)
                    return false;
            } else if(leapYear == false && month == 2) {
                if(day > 28)
                    return false;
            }

            return true;    
        } else return false;
    }
}
Pochmurnik
  • 780
  • 6
  • 18
  • 35
Sandeep.N
  • 21
  • 1
2

Calendar class has build-in displayName functionality:

Calendar.getInstance().getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); // Thu   

Calendar.SHORT -> Thu
Calendar.LONG_FORMAT -> Thursday

Available since Java 1.6. See also Oracle documentation

Leo Ufimtsev
  • 6,240
  • 5
  • 40
  • 48
2

There is a challenge on hackerrank Java Date and Time

personally, I prefer the LocalDate class.

  1. Import java.time.LocalDate
  2. Retrieve localDate by using "of" method which takes 3 arguments in "int" format.
  3. finally, get the name of that day using "getDayOfWeek" method.

There is one video on this challenge.

Java Date and Time Hackerrank solution

I hope it will help :)

Community
  • 1
  • 1
Ravi Solanki
  • 189
  • 3
  • 8
  • If any other coming here for HackerRank Java Date and Time and want to use that `Calendar` Class, Please note that the `set` method in Calendar takes months starting from 0. ie, `0 for January`. Thank you! – Sagar Devkota Jan 03 '19 at 12:30
2

method below retrieves seven days and return short name of days in List Array in Kotlin though, you can just reformat then in Java format, just presenting idea how Calendar can return short name

private fun getDayDisplayName():List<String>{
        val calendar = Calendar.getInstance()
        val dates= mutableListOf<String>()
        dates.clear()
        val s=   calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US)
        dates.add(s)
        for(i in 0..5){
            calendar.roll( Calendar.DATE, -1)
            dates.add(calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US))
        }
        return dates.toList()
    }

out put results like

I/System.out: Wed
    Tue
    Mon
    Sun
I/System.out: Sat
    Fri
    Thu
masokaya
  • 589
  • 4
  • 10
  • 1
    If OP is asking about Java, then it would be best to respond with Java. – mypetlion Jun 12 '19 at 19:14
  • 1
    There is no reason why we should want to use the `Calendar` class in 2019. It’s poorly designed and long outdated. Instead I recommend `LocalDate` and `DayOfWeek` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 13 '19 at 09:04
1
Calendar cal = Calendar.getInstance(desired date);
cal.setTimeInMillis(System.currentTimeMillis());
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

Get the day value by providing the current time stamp.

Sharath Kumar
  • 175
  • 1
  • 14
Amit
  • 91
  • 1
  • 3
  • 8
1
LocalDate date=LocalDate.now();

System.out.println(date.getDayOfWeek());//prints THURSDAY
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US) );  //prints Thu   
java.time.DayOfWeek is a enum which returns the singleton instance for the day-of-week of the weekday of the date.
Ayarnish
  • 29
  • 2
  • @Ayarnush How does your Answer add any value beyond [the Answer by Przemek](http://stackoverflow.com/a/33895008/642706) posted last month? – Basil Bourque Feb 11 '16 at 16:47
1
//to get day of any date

import java.util.Scanner; 
import java.util.Calendar; 
import java.util.Date;

public class Show {

    public static String getDay(String day,String month, String year){


            String input_date = month+"/"+day+"/"+year;

            Date now = new Date(input_date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            int final_day = (calendar.get(Calendar.DAY_OF_WEEK));

            String finalDay[]={"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"};

            System.out.println(finalDay[final_day-1]);

    }

    public static void main(String[] args) { 
            Scanner in = new Scanner(System.in); 
            String month = in.next(); 
        String day = in.next();
            String year = in.next();

            getDay(day, month, year);
    }

}
Abhishek
  • 11
  • 1
1

This works correctly...

java.time.LocalDate; //package related to time and date

It provides inbuilt method getDayOfWeek() to get the day of a particular week:

int t;
Scanner s = new Scanner(System.in);
t = s.nextInt();
s.nextLine();
 while(t-->0) { 
    int d, m, y;
    String ss = s.nextLine();
    String []sss = ss.split(" ");
    d=Integer.parseInt(sss[0]);
    m = Integer.parseInt(sss[1]);
    y = Integer.parseInt(sss[2]);

    LocalDate l = LocalDate.of(y, m, d); //method to get the localdate instance
    System.out.println(l.getDayOfWeek()); //this returns the enum DayOfWeek

To assign the value of enum l.getDayOfWeek() to a string, you could probably use the method of Enum called name() that returns the value of enum object.

David
  • 2,987
  • 1
  • 29
  • 35
  • 2
    Answers on Stack Overflow are better if they include some explanation as well as code snippet. – Basil Bourque Nov 18 '18 at 16:58
  • @David, I have been looking for difference in my edit and yours, I can't find it. Would be nice to get the info how to edit. – Pochmurnik Mar 04 '19 at 12:46
  • @OrdinaryDraft you added a `listHolidays.add(LocalDate.of(year, 1, 1));` to the answer. If you want to improve the answer, you should add your own. Hope that helps – David Mar 05 '19 at 11:53
  • Yes, I later checked my edit to compare with your version. It seems I copied that line by mistake. – Pochmurnik Mar 05 '19 at 12:15
0

You can use below method to get Day of the Week by passing a specific date,

Here for the set method of Calendar class, Tricky part is the index for the month parameter will starts from 0.

public static String getDay(int day, int month, int year) {

        Calendar cal = Calendar.getInstance();

        if(month==1){
            cal.set(year,0,day);
        }else{
            cal.set(year,month-1,day);
        }

        int dow = cal.get(Calendar.DAY_OF_WEEK);

        switch (dow) {
        case 1:
            return "SUNDAY";
        case 2:
            return "MONDAY";
        case 3:
            return "TUESDAY";
        case 4:
            return "WEDNESDAY";
        case 5:
            return "THURSDAY";
        case 6:
            return "FRIDAY";
        case 7:
            return "SATURDAY";
        default:
            System.out.println("GO To Hell....");
        }

        return null;
    }
Hardik Patel
  • 1,033
  • 1
  • 12
  • 16
  • 4
    This Answer is ill-advised, using terrible old date-time classes that are now legacy, supplanted by the java.time classes. Also, this code ignores the crucial issue of time zone after awkwardly applying a date-time class to a date-only problem. Instead, see the [correct Answer for java.time by Przemek](https://stackoverflow.com/a/33895008/642706). – Basil Bourque Nov 03 '17 at 14:55
0

Adding another way of doing it exactly what the OP asked for, without using latest inbuilt methods:

public static String getDay(String inputDate) {
    String dayOfWeek = null;
    String[] days = new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

    try {
        SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
        Date dt1 = format1.parse(inputDate);
        dayOfWeek = days[dt1.getDay() - 1];
    } catch(Exception e) {
        System.out.println(e);
    }

    return dayOfWeek;
}
Pochmurnik
  • 780
  • 6
  • 18
  • 35
Spriha
  • 107
  • 6
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Alex Riabov Jul 15 '18 at 10:31
  • 1
    This is in more than one way the discouraged way of doing it. Your code cannot be compiled. You shouldn’t use the long outdated and poorly designed classes `SimpleDateFormat` and `Date`. In particular you should not use the deprecated `getDay` method, it’s not reliable. And you shouldn’t use `if`-`else` for selecting among 7 values, this what we have `switch` for, or you may use an array. All in all your code is both longer and more complicated than it needs be. – Ole V.V. Jul 15 '18 at 14:11
  • 1
    And use the built-in month abbreviations rather than supplying your own. Simpler and less error-prone. – Ole V.V. Jul 15 '18 at 17:26
  • 1
    The troublesome classes used here were supplanted years ago by the *java.time* classes. Suggesting their use in 2018 is poor advice. – Basil Bourque Jul 15 '18 at 23:48
0

Get a Date for Today and then Find a week Day from it.

    LocalDate d = java.time.LocalDate.now();
    System.out.println(java.time.LocalDate.now()); 
    
    Calendar c = Calendar.getInstance();
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    System.out.println(dayOfWeek);
Waheed Khan
  • 104
  • 2
  • 10
  • 1
    It doesn’t really answer the question in the context of *For Example I have the date: "23/2/2010" (23th Feb 2010).* Also don’t use `Calendar`. It’s poorly designed and long outdated. Since you can use `LocalDate` from java.time, the modern Java date and time API, just use its `getDayOfWeek` method. – Ole V.V. Nov 24 '21 at 15:48
0

I use this

    String[] weekdays = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");

And then

weekdays[calendar.get(Calendar.DAY_OF_WEEK) - 1]

To get the particular weekday

imok1948
  • 81
  • 1
  • 3
  • 3
    Not recommended. In 2022 don’t use the `Calendar` class, it is cumbersome to work with and long outdated. And the names of the days of the week in may languages are built in, so exploit those and don’t code them yourself. – Ole V.V. Apr 25 '22 at 14:33
  • 1
    The terrible `Calendar` class was supplanted years ago by the modern *java.time* classes defined in JSR 310. Use `DayOfWeek` & `LocalDate` instead. – Basil Bourque Apr 27 '22 at 02:48
0

Using LocalDate, here is the class DayOfWeekConverter:

public class DayOfWeekConverter {

    public static String getDayOfWeekShort(String dateInput) {
        DayOfWeek dayOfWeek = getDayOfWeek(dateInput);
        return dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.US);
    }

    private static DayOfWeek getDayOfWeek(String dateInput) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/M/yyyy");
        LocalDate localDate = LocalDate.parse(dateInput, formatter);
        return localDate.getDayOfWeek();
    }

    public static int getDayOfWeekOrdinal(String dateInput) {
        DayOfWeek dayOfWeek = getDayOfWeek(dateInput);
        return dayOfWeek.getValue();
    }
}

Tests class DayOfWeekConverterTest:

class DayOfWeekConverterTest {

    @Test
    void givenStringDate_whenGetDayOfWeekShort_thenReturnTue() {
        assertEquals("Tue", DayOfWeekConverter.getDayOfWeekShort("23/2/2010"));
    }

    @Test
    void givenStringDate_whenGetDayOfWeekOrdinal_thenReturnTue() {
        assertEquals(2, DayOfWeekConverter.getDayOfWeekOrdinal("23/2/2010"));
    }
}
ognjenkl
  • 1,407
  • 15
  • 11
  • The code is correct and wisely uses the modern `LocalDate`. It would seem to me that it would make a bad fit into a well designed program, though. It would invite us to handle dates and days of the week as text in the code and use your class for conversion. We should not do that. We should handle `LocalDate` and `DayOfWeek` objects in our code and only convert them to and from strings for input and output. – Ole V.V. May 01 '23 at 06:47
  • 1
    Thank you @Ole for the insightful comment, I totally agree. I adjusted the class just as an answer to the questions. – ognjenkl May 02 '23 at 11:01
-3

Below is the two line of snippet using Java 1.8 Time API for your Requirement.

LocalDate localDate = LocalDate.of(Integer.valueOf(year),Integer.valueOf(month),Integer.valueOf(day));
String dayOfWeek = String.valueOf(localDate.getDayOfWeek());
Hardik Patel
  • 1,033
  • 1
  • 12
  • 16
  • 2
    The approach shown here has been covered already in at least 4 good Answers posted long ago. I see no value added by this duplicate. – Basil Bourque Dec 24 '17 at 17:31