java - 返回给定日期的星期几的 getDay() 方法不起作用

标签 java date dayofweek java.util.calendar

我正在尝试在 HackerRank 上完成名为 Java Date and Time 的任务。

任务

You are given a date. You just need to write the method, getDay, which returns the day on that date.For example, if you are given the date, August 14th 2017, the method should return MONDAY as the day on that date.

我已尽力完成任务,但得到的不是 null 结果就是 NullPointerException 错误。我想知道我哪里做错了。下面是我的代码:

提前致谢!

我的代码:

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String month = in.next();
        String day = in.next();
        String year = in.next();

        System.out.println(getDay(day, month, year));
    }

    public static String getDay(String day, String month, String year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.valueOf(year), (Integer.valueOf(month) - 1), Integer.valueOf(day));
        return cal.getDisplayName(cal.get(Calendar.DAY_OF_WEEK), Calendar.LONG, Locale.getDefault());
    }
}

最佳答案

您的返回已关闭;您不希望 cal.getDisplayName 的第一列中有 cal.get。目前,我用你的代码得到了月份名称。将其更改为

return cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());

并称它为

public static void main(String[] args) {
    System.out.println(getDay("14", "8", "2017"));
}

我得到了(如预期的那样)

Monday

在新代码中,我更喜欢java.time(Java 8+)中的新类,以及DateTimeFormatter - 比如,

public static String getDay(String day, String month, String year) {
    int y = Integer.parseInt(year), m = Integer.parseInt(month), d = Integer.parseInt(day);
    return java.time.format.DateTimeFormatter.ofPattern("EEEE")
            .format(LocalDate.of(y, m, d));
}

关于java - 返回给定日期的星期几的 getDay() 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48820696/

相关文章:

Java:连接到数据库以获取数据

c# - 在 C# 中使用枚举进行数学运算(例如 DayOfWeek)

postgresql - 在 Postgresql 中获取 ISO 日期的奇怪结果

java - 确定哪个面板被压入以及哪个面板被释放

java - Java反向数组方法是如何工作的?

java - 无法启动 Java 客户端 1.5.0 NoSuchMethodException

javascript - 如何将日期转换为整数?

iPhone 核心数据 : How to group fetched results by day?

php - 在 PHP 中将一种日期格式转换为另一种日期格式

java - 如何在 Java 的 Calendar 类中获取用户输入的日期而不是当前日期?