-2

I need a solution to return day (Monday,Tuesday...), when i have inputs like YEAR, MONTH, DATE.

public static String findDay(int month, int day, int year) { // code here }

    
Vaibhav Atray
  • 208
  • 4
  • 14
  • Welcome to Stack Overflow. Please learn that on this site you are required — also for your own sake — to perform a search before posting a question, and also in the question to report what you found and in what way it fell short of giving you what you wanted. Because you will often find a better answer faster that way, and because it allows us to write answers that more precisely and specifically address your issue. – Ole V.V. Apr 30 '21 at 16:40
  • Vaibhav Atray - The valuable comment by @OleV.V. will certainly help you to use SO in a better way in the future. At the same time, going by [this example](https://stackoverflow.com/questions/66665987/parse-oracle-date-to-java#comment117882069_66665987), this question doesn't have any duplicate on SO (so far I haven't been able to find an exact duplicate of this question). – Arvind Kumar Avinash Apr 30 '21 at 17:11
  • @ArvindKumarAvinash I didn’t find the exact same question asked before either. The skilled questioner may be able to piece an answer together from [this question](https://stackoverflow.com/questions/16499228/creating-java-date-object-from-year-month-day) and [this one](https://stackoverflow.com/questions/5270272/how-to-determine-day-of-week-by-passing-specific-date), for example. That reader should prefer to skip all the answers using `Calendar`, `SimpleDateFormat` and the other old date and time classes, though, and go for the ones using java.time like your own good answer does. – Ole V.V. Apr 30 '21 at 17:56

1 Answers1

3

Using the parameters, create a LocalDate from which you can get the weekday.

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

public class Main {
    public static void main(String args[]) {
        // Test
        System.out.println(findDay(2021, 4, 30));
    }

    public static String findDay(int year, int month, int day) {
        LocalDate date = LocalDate.of(year, month, day);
        return date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
    }
}

Output:

Friday

Learn more about the the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110