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 }
Advertisement
Answer
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.