问题
What is wrong with the below code? It gives wrong day for any date of the year.
import java.util.Scanner;
import java.util.Calendar;
public class Solution {
public static String getDay(String d, String m, String y) {
String[] days = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(y), Integer.parseInt(m), Integer.parseInt(d));
return days[c.get(Calendar.DAY_OF_WEEK) - 1];
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String m = in.next();
String d = in.next();
String y = in.next();
System.out.println(getDay(d, m, y));
}
}
回答1:
See the documentation for the Calendar
class: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#set-int-int-int-
The value for month is 0-indexed, so if you provide 3
as the month value, it is interpreted as "April".
回答2:
It’s easiest to have the Scanner
read int
values rather than strings:
int m = in.nextInt();
int d = in.nextInt();
int y = in.nextInt();
System.out.println(LocalDate.of(y, m, d).getDayOfWeek());
When I feed 5 4 2018
(today’s date), I get FRIDAY
, which is correct.
If you must use strings:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("M/d/u");
String m = in.next();
String d = in.next();
String y = in.next();
System.out.println(LocalDate.parse(m + '/' + d + '/' + y, dateFormatter).getDayOfWeek());
The Calendar
class you were using is long outdated, poorly designed and sometimes cumbersome to work with. Instead I recommend java.time
, the modern Java date and time API. It is so much nicer. For one little thing it numbers the months of the year in the same way humans do.
Also the names of the days of the week are built-in, so don’t reinvent the wheel. Your strings coincide with the names of the values of the DayOfWeek
enum in java.time
, so just print those to get the strings you want. If you don’t want all uppercase or you want the day names in another language, use DayOfWeek.getDisplayName
or a DateTimeFormatter
.
Link: Oracle tutorial: Date Time explaining how to use java.time
.
来源:https://stackoverflow.com/questions/50145304/java-calendar-day-of-week-gives-wrong-day