📜  在Java中使用公历打印星期几

📅  最后修改于: 2022-05-13 01:54:34.471000             🧑  作者: Mango

在Java中使用公历打印星期几

给定日期,您必须打印星期几。

例子:

Input : 2018 3 26
Output : Mon

Input : 2010 8 9
Output : Wed

这个想法是使用Java内置 API Gregorian Calendar
GregorianCalendar 是 Calendar 的具体子类,提供
世界上大部分地区使用的标准日历系统。
GregorianCalendar(int year, int month, int dayOfMonth) 构造一个
在默认时区中设置给定日期的 GregorianCalendar
使用默认语言环境。
创造了几个条件来检查的有效性
输入数据。如果发现输入错误,则Invalid
消息将作为输出打印。

// Necessary imports for using Gregorian Calendar
import java.util.Calendar;
import java.util.GregorianCalendar;
  
class GFG {
    static int method(int year, int month, int day)
    {
        // to check the validity of day of month
        int[] darr = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  
        // check validity of year and month
        if (year > 0 && (month > 0 && month <= 12)) {
  
            // check for a leap year and month of February
  
            if ((year % 4 == 0 || year % 400 == 0) && 
                month == 2 && (day > 0 && day <= 29)) {
  
                // month starts at zero, so we need to put ( month - 1 ).
                Calendar calendar = new GregorianCalendar(year, month - 1, day);
                return calendar.get(Calendar.DAY_OF_WEEK);
            }
            else {
  
                // check the range of day of month
                if (day > 0 && day <= darr[month - 1]) {
  
                    // month starts at zero, so we need to put ( month - 1 ).
                    Calendar calendar = new GregorianCalendar(year, month - 1, day);
                    return calendar.get(Calendar.DAY_OF_WEEK);
                }
                else
                    return 0;
            }
        }
        else
            return 0;
    }
    public static void main(String[] args)
    {
        String[] dayofweek = { "Invalid", "Sun", "Mon", "Tue",
                                "Wed", "Thur", "Fri", "Sat" };
        int y = 2018, m = 3, d = 26;
        System.out.println(dayofweek[method(y, m, d)]);
    }
}
输出:
Mon