简体   繁体   English

Java Calendar.DAY_OF_WEEK 给出错误的一天

[英]Java Calendar.DAY_OF_WEEK gives wrong day

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));
    }
}

See the documentation for the Calendar class: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#set-int-int-int-请参阅Calendar类的文档: 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".月份的值是 0 索引的,因此如果您提供3作为月份值,它会被解释为“四月”。

It's easiest to have the Scanner read int values rather than strings:Scanner读取int值而不是字符串是最简单的:

    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.当我喂5 4 2018 (今天的日期)时,我得到FRIDAY ,这是正确的。

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.您使用的Calendar类早已过时,设计不佳,有时使用起来很麻烦。 Instead I recommend java.time , the modern Java date and time API.相反,我推荐java.time ,现代 Java 日期和时间 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.您的字符串与java.time DayOfWeek枚举的值的名称一致,因此只需打印它们即可获得您想要的字符串。 If you don't want all uppercase or you want the day names in another language, use DayOfWeek.getDisplayName or a DateTimeFormatter .如果您不想要全部大写或想要其他语言的日期名称,请使用DayOfWeek.getDisplayNameDateTimeFormatter

Link: Oracle tutorial: Date Time explaining how to use java.time .链接: Oracle 教程:解释如何使用java.time日期时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM