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

前端 未结 3 713
礼貌的吻别
礼貌的吻别 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: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]);
    

提交回复
热议问题