Reputation: 33741
How can I get the day of week or month as a String? Without having to do something like:
DateTime now = DateTime.now();
String dayOfWeek = null;
switch(now.getDayOfWeek()) {
case DateTimeConstants.MONDAY:
dayOfWeek = "Monday";
break;
case DateTimeConstants.TUESDAY:
dayOfWeek = "Tuesday";
break;
case DateTimeConstants.WEDNESDAY:
dayOfWeek = "Wednesday";
break;
case DateTimeConstants.THURSDAY:
dayOfWeek = "Thursday";
break;
case DateTimeConstants.FRIDAY:
dayOfWeek = "Friday";
break;
case DateTimeConstants.SATURDAY:
dayOfWeek = "Saturday";
break;
case DateTimeConstants.SUNDAY:
dayOfWeek = "Sunday";
break;
}
Upvotes: 5
Views: 7729
Reputation: 79085
java.time
Shown below is a notice on the Joda-Time Home Page:
Note that from Java SE 8 onwards, users are asked to migrate to
java.time
(JSR-310) - a core part of the JDK which replaces this project.
Your question:
How can I get the day of week or month as a String?
java.time
APIZonedDateTime#now
.ZonedDateTime#getDayOfWeek--
and ZonedDateTime#getMonth
to get the day of the week and month enum
constants respectively from the ZonedDateTime
instance.getDisplayName(TextStyle, Locale)
function of these enums to get the String
in the desired locale.Demo:
class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the system default time zone
// Change it to the desired time zone e.g. ZoneId.of("Europe/Paris")
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.now(zoneId);
DayOfWeek dayOfWeek = zdt.getDayOfWeek();
System.out.println("Day of week: " + dayOfWeek);
System.out.println(dayOfWeek.getDisplayName(
TextStyle.FULL, Locale.ENGLISH));
System.out.println(dayOfWeek.getDisplayName(
TextStyle.FULL, Locale.forLanguageTag("hi"))); // Hindi
System.out.println(dayOfWeek.getDisplayName(
TextStyle.FULL, Locale.forLanguageTag("fr")));// French
Month month = zdt.getMonth();
System.out.println("Month: " + month);
System.out.println(month.getDisplayName(
TextStyle.FULL, Locale.ENGLISH));
System.out.println(month.getDisplayName(
TextStyle.FULL, Locale.forLanguageTag("hi"))); // Hindi
System.out.println(month.getDisplayName(
TextStyle.FULL, Locale.forLanguageTag("fr"))); // French
}
}
Output:
Day of week: THURSDAY
Thursday
गुरुवार
jeudi
Month: JANUARY
January
जनवरी
janvier
Learn more about the modern Date-Time API from Trail: Date Time.
Upvotes: 2
Reputation: 33741
Well, apparently it's just dateTime.dayOfWeek().getAsText();
as documented here.
Upvotes: 13
Reputation: 973
You can create DateTime extension method with the above logic and use wherever required without repeating the whole logic.
Upvotes: 0