How to determine day of week by passing specific date?

前端 未结 25 1852
夕颜
夕颜 2020-11-22 05:12

For Example I have the date: \"23/2/2010\" (23th Feb 2010). I want to pass it to a function which would return the day of week. How can I do this?

I

25条回答
  •  轮回少年
    2020-11-22 05:30

    tl;dr

    Using 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.
             ) 
    

    Tue

    See this code run live at IdeOne.com (but only Locale.US works there).

    java.time

    See my example code above, and see the correct Answer for java.time by Przemek.

    Ordinal number

    if just the day ordinal is desired, how can that be retrieved?

    For ordinal number, consider passing around the DayOfWeek enum object instead such as DayOfWeek.TUESDAY. Keep in mind that a DayOfWeek is a smart object, not just a string or mere integer number. Using those enum objects makes your code more self-documenting, ensures valid values, and provides type-safety.

    But if you insist, ask DayOfWeek for a number. You get 1-7 for Monday-Sunday per the ISO 8601 standard.

    int ordinal = myLocalDate.getDayOfWeek().getValue() ;
    

    Joda-Time

    UPDATE: The Joda-Time project is now in maintenance mode. The team advises migrating to the java.time classes. The java.time framework is built into Java 8 (as well as back-ported to Java 6 & 7 and further adapted to Android).

    Here is example code using the Joda-Time library version 2.4, as mentioned in the accepted answer by Bozho. Joda-Time is far superior to the java.util.Date/.Calendar classes bundled with Java.

    LocalDate

    Joda-Time offers the LocalDate class to represent a date-only without any time-of-day or time zone. Just what this Question calls for. The old java.util.Date/.Calendar classes bundled with Java lack this concept.

    Parse

    Parse the string into a date value.

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

    Extract

    Extract from the date value the day of week number and name.

    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 );
    

    Dump

    Dump to console.

    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

    When run.

    input: 23/2/2010
    localDate: 2010-02-23
    dayOfWeek: 2
    output: Tue
    outputQuébécois: mar.
    

    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

提交回复
热议问题