From the day week number get the day name with Joda Time

前端 未结 3 699
礼貌的吻别
礼貌的吻别 2020-12-03 10:40

I have a day of the week number: 2 (which should match to Tuesday if week start on Monday).

From this number is there a way to get the name of the day in Ja

相关标签:
3条回答
  • 2020-12-03 11:18

    Using Joda you can do this:

     DateTime curTime = new DateTime();
     curTime.dayOfWeek().getAsText(Locale.ENGLISH);
    

    Replace Locale with whatever your Locale is.

    Should return a week day name such as Monday or Tuesday

    0 讨论(0)
  • 2020-12-03 11:24

    You can do it yourself

    String[] dayNames = new String[]{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    String name = dayNames[day-1];
    

    And this even does not require any library :)

    0 讨论(0)
  • 2020-12-03 11:25

    Joda-Time

    At least this works, although I consider it as not so nice:

    LocalDate date = new LocalDate();
    date = date.withDayOfWeek(2);
    System.out.println(DateTimeFormat.forPattern("EEEE").print(date));
    

    Unfortunately Joda-Time does not offer an enum for the day of week (java.time does). I have not quickly found another way in the huge api. Maybe some Joda-experts know a better solution.

    Added (thanks to @BasilBourque):

    LocalDate date = new LocalDate();
    date = date.withDayOfWeek(2);
    System.out.println(date.dayOfWeek().getAsText());
    

    java.time

    In java.time (JSR 310, Java 8 and later), use the DayOfWeek enum.

    int day = 2;
    System.out.println( DayOfWeek.of(2).getDisplayName(TextStyle.FULL, Locale.ENGLISH) );
    // Output: Tuesday
    

    You can use a particular enum instance directly rather than a magic number like 2. The DayOfWeek enum provides an instance for each day of week such as DayOfWeek.TUESDAY.

    System.out.println( DayOfWeek.TUESDAY.getDisplayName(TextStyle.FULL, Locale.ENGLISH) );
    // Output: Tuesday
    

    Old JDK

    For making it complete, here the solution of old JDK:

    int day = 2;
    DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.ENGLISH);
    System.out.println(dfs.getWeekdays()[day % 7 + 1]);
    
    0 讨论(0)
提交回复
热议问题