返回以给定日期的所有大写字母形式存储星期几的字符串字符串[关闭]

问题描述 投票:-1回答:1

我对Java和编程领域来说是非常陌生的人,希望获得有关问题的帮助。我已经被赋予了这个问题来从给定的日期获取星期几并将其作为字符串返回给所有大写字母。这是到目前为止我得到的代码和提示

import java.time.LocalDate;

public class ChallengeThree {

    public static String dayOfWeek(String date) {


        // CODE1: Write code to return the day of the week of the String date
        //        using the DateUtil class at the bottom of this file


        // ====================================
        // Do not change the code after this
    }

    public static void main(String[] args) {
        String theDayOfWeek = dayOfWeek("2000-01-01");
        String expected = "SATURDAY";
        // Expected output is
        // true
        System.out.println(theDayOfWeek == expected);
    }
}

class DateUtil {

    LocalDate theDate;

    public DateUtil(String date) {
        /**
         * Initialize the theDate field using the String date argument
         * Arguments
         * date - a String storing a local date, such as "2000-01-01"
         */

        // ====================================
        // Do not change the code before this

        // CODE2: Write code to initialize the date field of the class
        LocalDate theDate = date;

        // ====================================
        // Do not change the code after this
    }

    public String dayOfWeek() {
        /**
         * Return a String the day of the week represented by theDate
         */

        // ====================================
        // Do not change the code before this

        // CODE3: Write code to return the String day of the week of theDate


        // ====================================
        // Do not change the code after this
    }
}
java datetime dayofweek java-date
1个回答
0
投票

首先,您需要使用LocalDate#parse将字符串解析为LocalDate。然后,您可以简单地使用LocalDate#getDayOfWeek()#toString()方法以String的形式返回星期几的名称,因为它是一个枚举元素,按惯例已经全部大写了。

    public static String dayOfWeek(String date) {
        return new DateUtil(date).dayOfWeek();
    }

    public static void main(String[] args) {
        String theDayOfWeek = dayOfWeek("2000-01-01");

        String expected = "SATURDAY";

        System.out.println(theDayOfWeek.equals(expected));
    }

    static class DateUtil {

        LocalDate theDate;

        public DateUtil(String date) {
            theDate = LocalDate.parse(date);
        }

        public String dayOfWeek() {
            return theDate.getDayOfWeek().toString();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.