Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jodatime

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 Java using Joda Time? In javascript it has been quite easy to do it using moment.js:

moment().day(my number)
like image 228
Begoodpy Avatar asked Jan 03 '14 16:01

Begoodpy


1 Answers

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]);
like image 103
Meno Hochschild Avatar answered Nov 15 '22 21:11

Meno Hochschild