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

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

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


当前回答

是的。根据具体情况:

You can use java.util.Calendar: Calendar c = Calendar.getInstance(); c.setTime(yourDate); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); if you need the output to be Tue rather than 3 (Days of week are indexed starting at 1 for Sunday, see Calendar.SUNDAY), instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version") if you have your input as string, rather than Date, you should use SimpleDateFormat to parse it: new SimpleDateFormat("dd/M/yyyy").parse(dateString) you can use joda-time's DateTime and call dateTime.dayOfWeek() and/or DateTimeFormat. edit: since Java 8 you can now use java.time package instead of joda-time

其他回答

  String inputDate = "01/08/2012";
  SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
  Date dt1 = format1.parse(input_date);
  DateFormat format2 = new SimpleDateFormat("EEEE"); 
  String finalDay = format2.format(dt1);

使用此代码从输入日期中查找日期名称。简单且经过良好测试。

方法下面检索七天,并返回短名称的天在列表数组在Kotlin,你可以重新格式化然后在Java格式,只是提出想法日历可以返回短名称

private fun getDayDisplayName():List<String>{
        val calendar = Calendar.getInstance()
        val dates= mutableListOf<String>()
        dates.clear()
        val s=   calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US)
        dates.add(s)
        for(i in 0..5){
            calendar.roll( Calendar.DATE, -1)
            dates.add(calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US))
        }
        return dates.toList()
    }

结果是这样的

I/System.out: Wed
    Tue
    Mon
    Sun
I/System.out: Sat
    Fri
    Thu

一句话回答:

return LocalDate.parse("06/02/2018",DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();

使用的例子:

public static String getDayOfWeek(String date){
  return LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();
}

public static void callerMethod(){
   System.out.println(getDayOfWeek("06/02/2018")); //TUESDAY
}

可以使用以下代码片段进行输入,如(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();

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

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

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

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

Java日期和时间Hackerrank解决方案

我希望它会有所帮助:)