How to determine day of week by passing specific date?

前端 未结 25 1428
夕颜
夕颜 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:28

    You can try the following code:

    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));
       }
    }
    
    0 讨论(0)
  • 2020-11-22 05:29

    Calendar class has build-in displayName functionality:

    Calendar.getInstance().getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); // Thu   
    
    Calendar.SHORT -> Thu
    Calendar.LONG_FORMAT -> Thursday
    

    Available since Java 1.6. See also Oracle documentation

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 05:31
    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:34
    private String getDay(Date date){
    
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
        //System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());                       
        return simpleDateFormat.format(date).toUpperCase();
    }
    
    private String getDay(String dateStr){
        //dateStr must be in DD-MM-YYYY Formate
        Date date = null;
        String day=null;
    
        try {
            date = new SimpleDateFormat("DD-MM-YYYY").parse(dateStr);
    
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
            //System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
            day = simpleDateFormat.format(date).toUpperCase();
    
    
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    
        return day;
    }
    
    0 讨论(0)
  • 2020-11-22 05:35
      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);
    

    Use this code for find the Day name from a input date.Simple and well tested.

    0 讨论(0)
提交回复
热议问题