例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?

在这个例子中,函数应该返回String "Tue"。

此外,如果只需要日期顺序,如何检索?


当前回答

LocalDate date=LocalDate.now();

System.out.println(date.getDayOfWeek());//prints THURSDAY
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US) );  //prints Thu   
java.time.DayOfWeek is a enum which returns the singleton instance for the day-of-week of the weekday of the date.

其他回答

下面是两行代码片段,使用Java 1.8 Time API满足您的需求。

LocalDate localDate = LocalDate.of(Integer.valueOf(year),Integer.valueOf(month),Integer.valueOf(day));
String dayOfWeek = String.valueOf(localDate.getDayOfWeek());

为今天找一个日期,然后从中找出一个星期。

    LocalDate d = java.time.LocalDate.now();
    System.out.println(java.time.LocalDate.now()); 
    
    Calendar c = Calendar.getInstance();
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    System.out.println(dayOfWeek);

有一个关于hackerrank Java日期和时间的挑战

就我个人而言,我更喜欢LocalDate类。

进口java.time.LocalDate 使用“of”方法检索localDate,该方法包含3个参数 “int”格式。 最后,使用“getDayOfWeek”方法获取当天的名称。

有一个关于这个挑战的视频。

Java日期和时间Hackerrank解决方案

我希望它会有所帮助:)

可以使用以下代码片段进行输入,如(day = "08", month = "05", year = "2015",输出将是"WEDNESDAY")

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
calendar.set(Calendar.MONTH, (Integer.parseInt(month)-1));
calendar.set(Calendar.YEAR, Integer.parseInt(year));
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();

通过使用java.util.scanner包给用户输入日期、月和年来查找星期几的程序:

import java.util.Scanner;

public class Calender {
    public static String getDay(String day, String month, String year) {

        int ym, yp, d, ay, a = 0;
        int by = 20;
        int[] y = new int[]{6, 4, 2, 0};
        int[] m = new int []{0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};

        String[] wd = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

        int gd = Integer.parseInt(day);
        int gm = Integer.parseInt(month);
        int gy = Integer.parseInt(year);

        ym = gy % 100;
        yp = ym / 4;
        ay = gy / 100;

        while (ay != by) {
            by = by + 1;
            a = a + 1;

            if(a == 4) {
                a = 0;
            }
        }

        if ((ym % 4 == 0) && (gm == 2)) {
            d = (gd + m[gm - 1] + ym + yp + y[a] - 1) % 7;
        } else
            d = (gd + m[gm - 1] + ym + yp + y[a]) % 7;

        return wd[d];
    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        String day = in.next();
        String month = in.next();
        String year = in.next();

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