如何通过特定日期确定星期几?

evi*_*iko 169 java date

例如,我有日期:"2010年2月23日"(2010年2月23日).我想将它传递给一个可以返回星期几的函数.我怎样才能做到这一点?

在此示例中,函数应返回String"Tue".

此外,如果只需要日序,那么如何检索?

Boz*_*zho 323

是.根据您的确切情况:

  • 你可以使用java.util.Calendar:

    Calendar c = Calendar.getInstance();
    c.setTime(yourDate);
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果你需要的输出为Tue,而不是3(本周日进行索引从1开始),而不是通过日历打算,只是格式化字符串: new SimpleDateFormat("EE").format(date)(EE意为"一周中的一天,短版")

  • 如果您将输入作为字符串,而不是Date,您应该使用SimpleDateFormat它来解析它:new SimpleDateFormat("dd/M/yyyy").parse(dateString)

  • 你可以使用joda-time DateTime和电话dateTime.dayOfWeek()和/或DateTimeFormat.

  • 星期几从星期日开始,所以我认为星期二将是3. (19认同)
  • 在其他要注意的事项中,如果使用整数(而不是通过解析字符串)在Calendar对象中设置日期,那么请注意月份数是从零开始的,因此1月为0,12月为11. (12认同)
  • @RenniePet:好的.您还可以在`Calendar`类中使用常量,例如`Calendar.SUNDAY`或`Calendar.JANUARY`. (4认同)
  • 撰写时,这个答案是一个很好的答案。今天,您将需要使用已经过时的类Calendar,Date和DateTimeFormat(以及Joda time),并使用Java 8 Java.time类,例如YearMonth或LocalDate。在[此答案](http://stackoverflow.com/a/33895008/5772882)中查看更多信息。 (2认同)
  • 仅供参考,麻烦的旧日期时间类,例如[`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html),[` java.util.Calendar`](https://docs.oracle.com/javase/9​​/docs/api/java/util/Calendar.html)和`java.text.SimpleDateFormat`现在都是[旧版](https ://en.wikipedia.org/wiki/Legacy_system),由[java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html取代)内置在Java 8和Java 9中的类。请参见[Oracle教程](https://docs.oracle.com/javase/tutorial/datetime/TOC.html)。 (2认同)

JDG*_*ide 59

  String input_date="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);
Run Code Online (Sandbox Code Playgroud)

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

  • 仅供参考,麻烦的旧日期时间类,例如 [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html),[` java.util.Calendar`](https://docs.oracle.com/javase/9​​/docs/api/java/util/Calendar.html) 和 `java.text.SimpleDateFormat` 现在是 [legacy](https ://en.wikipedia.org/wiki/Legacy_system),由 [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) 取代) Java 8 和 Java 9 中内置的类。请参阅 [Oracle 教程](https://docs.oracle.com/javase/tutorial/datetime/TOC.html)。 (3认同)

Nik*_*tov 25

只需使用SimpleDateFormat.

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", java.util.Locale.ENGLISH);
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("EEE, d MMM yyyy");
String sMyDate = sdf.format(myDate);
Run Code Online (Sandbox Code Playgroud)

其结果是: 2013年12月28日星期六

默认构造函数采用"默认" Locale,因此在需要特定模式时请小心使用它.

public SimpleDateFormat(String pattern) {
    this(pattern, Locale.getDefault(Locale.Category.FORMAT));
}
Run Code Online (Sandbox Code Playgroud)


Bas*_*que 20

TL;博士

使用java.time ...

LocalDate.parse(                               // Generate `LocalDate` object from String input.
             "23/2/2010" ,
             DateTimeFormatter.ofPattern( "d/M/uuuu" ) 
         )                                    
         .getDayOfWeek()                       // Get `DayOfWeek` enum object.
         .getDisplayName(                      // Localize. Generate a String to represent this day-of-week.
             TextStyle.SHORT_STANDALONE ,      // How long or abbreviated. Some languages have an alternate spelling for "standalone" use (not so in English).
             Locale.US                         // Or Locale.CANADA_FRENCH and such. Specify a `Locale` to determine (1) human language for translation, and (2) cultural norms for abbreviation, punctuation, etc.
         ) 
Run Code Online (Sandbox Code Playgroud)

星期二

请参阅此代码在IdeOne.com上运行(但仅Locale.US适用于此处).

java.time

请参阅上面的示例代码,并查看Przemek对java.time正确答案.

序数词

如果只需要那天的序数,怎么能找回?

对于序数,请考虑绕过DayOfWeekenum对象,例如DayOfWeek.TUESDAY.请记住,a DayOfWeek是一个智能对象,而不仅仅是字符串或纯粹的整数.使用这些枚举对象可以使您的代码更加自我记录,确保有效值,并提供类型安全性.

但如果你坚持,请问DayOfWeek一个号码.根据ISO 8601标准,您可以在周一至周日获得1-7 .

int ordinal = myLocalDate.getDayOfWeek().getValue() ;
Run Code Online (Sandbox Code Playgroud)

乔达时间

更新: Joda-Time项目现在处于维护模式.该团队建议迁移到java.time类.java.time框架内置于Java 8中(以及后端移植到Java 6和7进一步适用于Android).

下面是使用Joda-Time库2.4版的示例代码,如Bozho接受的答案中所述.Joda-Time远远优于与Java捆绑的java.util.Date/.Calendar类.

LocalDate

Joda-Time提供的LocalDate课程仅代表日期,没有任何时间或时区.正是这个问题所要求的.与Java捆绑在一起的旧java.util.Date/.Calendar类缺少这个概念.

解析

将字符串解析为日期值.

String input = "23/2/2010";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( input );
Run Code Online (Sandbox Code Playgroud)

提取

从日期值中提取周数和名称的日期.

int dayOfWeek = localDate.getDayOfWeek(); // Follows ISO 8601 standard, where Monday = 1, Sunday = 7.
Locale locale = Locale.US;  // Locale specifies the human language to use in determining day-of-week name (Tuesday in English versus Mardi in French).
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "E" ).withLocale( locale );
String output = formatterOutput.print( localDate ); // 'E' is code for abbreviation of day-of-week name. See Joda-Time doc.
String outputQuébécois = formatterOutput.withLocale( Locale.CANADA_FRENCH ).print( localDate );
Run Code Online (Sandbox Code Playgroud)

倾倒

转储到控制台.

System.out.println( "input: " + input );
System.out.println( "localDate: " + localDate ); // Defaults to ISO 8601 formatted strings.
System.out.println( "dayOfWeek: " + dayOfWeek );
System.out.println( "output: " + output );
System.out.println( "outputQuébécois: " + outputQuébécois );
Run Code Online (Sandbox Code Playgroud)

跑步时

input: 23/2/2010
localDate: 2010-02-23
dayOfWeek: 2
output: Tue
outputQuébécois: mar.
Run Code Online (Sandbox Code Playgroud)

关于java.time

java.time框架是建立在Java 8和更高版本.这些类取代麻烦的老传统日期时间类,如java.util.Date,Calendar,和SimpleDateFormat.

现在处于维护模式Joda-Time项目建议迁移到java.time类.

要了解更多信息,请参阅Oracle教程.并搜索Stack Overflow以获取许多示例和解释.规范是JSR 310.

从哪里获取java.time类?

ThreeTen-额外项目与其他类扩展java.time.该项目是未来可能添加到java.time的试验场.您可以在此比如找到一些有用的类Interval,YearWeek,YearQuarter,和更多.


Mim*_*han 14

对于Java 8 或更高版本,最好使用Localdate

import java.time.LocalDate;

public static String findDay(int month, int day, int year) {

    LocalDate localDate = LocalDate.of(year, month, day);

    java.time.DayOfWeek dayOfWeek = localDate.getDayOfWeek();
    System.out.println(dayOfWeek);

    return dayOfWeek.toString();
}
Run Code Online (Sandbox Code Playgroud)

注意:如果输入是字符串/用户定义的,那么您应该将其解析为int


Prz*_*mek 12

java.time

使用java.time内置于Java 8及更高版本的框架.

枚举可以生成自动定位于人类语言和的文化规范当天的名称的字符串.指定a 表示您需要长格式或缩写名称.DayOfWeek LocaleTextStyle

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
import java.util.Locale
import java.time.DayOfWeek;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");
LocalDate date = LocalDate.parse("23/2/2010", formatter); // LocalDate = 2010-02-23
DayOfWeek dow = date.getDayOfWeek();  // Extracts a `DayOfWeek` enum object.
String output = dow.getDisplayName(TextStyle.SHORT, Locale.US); // String = Tue
Run Code Online (Sandbox Code Playgroud)

  • @codepeaker 在 [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) 项目中,大部分 *java.time* 功能都向后移植到 Java 6 和 Java 7。在 [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) 中进一步适用于早期的 Android (<26)。请参阅[*如何使用 ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706)。 (2认同)

小智 8

public class TryDateFormats {
    public static void main(String[] args) throws ParseException {
        String month = "08";
        String day = "05";
        String year = "2015";
        String inputDateStr = String.format("%s/%s/%s", day, month, year);
        Date inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);
        String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
        System.out.println(dayOfWeek);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以尝试以下代码:

import java.time.*;

public class Test{
   public static void main(String[] args) {
      DayOfWeek dow = LocalDate.of(2010,Month.FEBRUARY,23).getDayOfWeek();
      String s = String.valueOf(dow);
      System.out.println(String.format("%.3s",s));
   }
}
Run Code Online (Sandbox Code Playgroud)


ala*_*inm 5

另一种"有趣"的方式是使用世界末日算法.这是一种更长的方法,但如果您不需要创建具有给定日期的Calendar对象,它也会更快.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 *
 * @author alain.janinmanificat
 */
public class Doomsday {

    public static HashMap<Integer, ArrayList<Integer>> anchorDaysMap = new HashMap<>();
    public static HashMap<Integer, Integer> doomsdayDate = new HashMap<>();
    public static String weekdays[] = new DateFormatSymbols(Locale.FRENCH).getWeekdays();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ParseException, ParseException {

        // Map is fed manually but we can use this to calculate it : http://en.wikipedia.org/wiki/Doomsday_rule#Finding_a_century.27s_anchor_day
        anchorDaysMap.put(Integer.valueOf(0), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1700));
                add(Integer.valueOf(2100));
                add(Integer.valueOf(2500));
            }
        });

        anchorDaysMap.put(Integer.valueOf(2), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1600));
                add(Integer.valueOf(2000));
                add(Integer.valueOf(2400));
            }
        });

        anchorDaysMap.put(Integer.valueOf(3), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1500));
                add(Integer.valueOf(1900));
                add(Integer.valueOf(2300));
            }
        });

        anchorDaysMap.put(Integer.valueOf(5), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1800));
                add(Integer.valueOf(2200));
                add(Integer.valueOf(2600));
            }
        });

        //Some reference date that always land on Doomsday
        doomsdayDate.put(Integer.valueOf(1), Integer.valueOf(3));
        doomsdayDate.put(Integer.valueOf(2), Integer.valueOf(14));
        doomsdayDate.put(Integer.valueOf(3), Integer.valueOf(14));
        doomsdayDate.put(Integer.valueOf(4), Integer.valueOf(4));
        doomsdayDate.put(Integer.valueOf(5), Integer.valueOf(9));
        doomsdayDate.put(Integer.valueOf(6), Integer.valueOf(6));
        doomsdayDate.put(Integer.valueOf(7), Integer.valueOf(4));
        doomsdayDate.put(Integer.valueOf(8), Integer.valueOf(8));
        doomsdayDate.put(Integer.valueOf(9), Integer.valueOf(5));
        doomsdayDate.put(Integer.valueOf(10), Integer.valueOf(10));
        doomsdayDate.put(Integer.valueOf(11), Integer.valueOf(7));
        doomsdayDate.put(Integer.valueOf(12), Integer.valueOf(12));

        long time = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {

            //Get a random date
            int year = 1583 + new Random().nextInt(500);
            int month = 1 + new Random().nextInt(12);
            int day = 1 + new Random().nextInt(7);

            //Get anchor day and DoomsDay for current date
            int twoDigitsYear = (year % 100);
            int century = year - twoDigitsYear;
            int adForCentury = getADCentury(century);
            int dd = ((int) twoDigitsYear / 12) + twoDigitsYear % 12 + (int) ((twoDigitsYear % 12) / 4);

            //Get the gap between current date and a reference DoomsDay date
            int referenceDay = doomsdayDate.get(month);
            int gap = (day - referenceDay) % 7;

            int result = (gap + adForCentury + dd) % 7;

            if(result<0){
                result*=-1;
            }
            String dayDate= weekdays[(result + 1) % 8];
            //System.out.println("day:" + dayDate);
        }
        System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 80

         time = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            Calendar c = Calendar.getInstance();
            //I should have used random date here too, but it's already slower this way
            c.setTime(new SimpleDateFormat("dd/MM/yyyy").parse("12/04/1861"));
//            System.out.println(new SimpleDateFormat("EE").format(c.getTime()));
            int result2 = c.get(Calendar.DAY_OF_WEEK);
//            System.out.println("day idx :"+ result2);
        }
        System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 884
    }

    public static int getADCentury(int century) {
        for (Map.Entry<Integer, ArrayList<Integer>> entry : anchorDaysMap.entrySet()) {
            if (entry.getValue().contains(Integer.valueOf(century))) {
                return entry.getKey();
            }
        }
        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

...
import java.time.LocalDate;
...
//String month = in.next();
int mm = in.nextInt();
//String day = in.next();
int dd = in.nextInt();
//String year = in.next();
int yy = in.nextInt();
in.close();
LocalDate dt = LocalDate.of(yy, mm, dd);
System.out.print(dt.getDayOfWeek());
Run Code Online (Sandbox Code Playgroud)


小智 5

可以使用以下代码片段进行输入,例如 (day = "08", month = "05", year = "2015" and output will be "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();
Run Code Online (Sandbox Code Playgroud)


Sah*_*bra 5

一行回答:

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

用法示例:

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
}
Run Code Online (Sandbox Code Playgroud)