2

I want names of all days in a week, but i have to create Enum(can be achieved by other ways too).

Another way is to get the constant from calendar class and store them manually in Collection.

But, Is there any method in Java Date-Time API to get Collection of all Days name in a week or Collection of all months name in year.

Prateek
  • 12,014
  • 12
  • 60
  • 81
  • What about http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeConstants.html? Seems like this is all that Joda offers by default. – Natix Sep 19 '14 at 08:37
  • See [DateFormatSymbols#getWeekdays()](http://docs.oracle.com/javase/7/docs/api/java/text/DateFormatSymbols.html) for names of all days in a week !! – Wundwin Born Sep 19 '14 at 08:39
  • Above approach will return this : [, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]. That is , No of days is 8. Why is it so ? – Prateek Sep 19 '14 at 08:40
  • Note that the DateFormatSymbols are locale sensitive. This is fine is you just want to print the day names into the UI, but it might not be very suitable for any date-time based logic. – Natix Sep 19 '14 at 08:42
  • @Natix care to elaborate as to why this would be a problem? – Mateusz Dymczyk Sep 19 '14 at 08:54
  • @MateuszDymczyk Suppose you want to implement a method that determines whether a given day is on weekend. Because you represent days only as strings, the method would need to look like this `boolean isWeekend(String day)`. But this wouldn't work, because the day name can be everything from `Saturday` to `Samstag` or whatever else based on the given locale. So for the method to be correct, it would have to be changed to `boolean isWeekend(String day, Locale locale)`. And passing the corresponding locale around with the day name is just cumbersome. – Natix Sep 19 '14 at 09:07
  • @Natix if you are working with the same locale then it won't be a problem. If you can have multiple locale in your app then there's no other way than to either have 1) a huge mapping of all possible names of all days in all locale to some unique values (i.e. [Saturday,Samstag,... -> 7] or 2) to pass the locale to the function. I still don't see how ```DateFormatSymbols``` is at fault here. – Mateusz Dymczyk Sep 19 '14 at 09:14
  • unless you want an out-of-the-box method which will give you the mapping I mentioned above, then yes that would be a nice method but I've never seen one. Last but not least OP mentioned ```Collection of all Days name```, hard to do that in a locale agnostic way :-) – Mateusz Dymczyk Sep 19 '14 at 09:17
  • @MateuszDymczyk This is about separating data from their visual representation. You don't work with dates in the form of strings. You have a strongly typed class such as Date/Calendar/DateTime which holds the semantics and you perform any application logic on them. Only in the final step (that is when showing them in the UI), you use some locale-aware formatter and print the dates to the user. But you never count the number of days directly between two strings such "19.9.2014" and "1.1.2015". You always convert them into a semantic data structure first. The same logic applies for week days. – Natix Sep 19 '14 at 09:23
  • 1
    And the out-of-the-box method is actually present in Java 8: `java.time.DayOfWeek.getDisplayName(TextStyle style, Locale locale)`. :) – Natix Sep 19 '14 at 09:26
  • @Natix I understand this and fully agree but the initial question was regarding the names, so I don't understand how locale are a problem in this case. Apparently OP needs names for something, not numbers. I thought you were talking about this specific case. – Mateusz Dymczyk Sep 19 '14 at 09:27
  • I'm not sure what issue is OP actually trying to solve. If printing the day names is enough for his case, then DateFormatSymbols are just fine. But as I mentioned in my 1st comment, this isn't a generally useful class for more sophisticated logic. – Natix Sep 19 '14 at 09:30

3 Answers3

5

Yes you can using DateFormatSymbols:

DateFormatSymbols symbols = new DateFormatSymbols(new Locale("en"));
String[] days = symbols.getWeekdays();
String[] months = symbols.getMonths();

There are also methods for short names (for en it would be Sat etc.) and of course you can choose your locale. Works with Java 1.6+.

@Edit: as to why this returns 8 values for days, if you check the Calendar class they start counting days from 1 to 7 so I guess DateFormatSymbols doesn't want to fool around with subtracting one and they just went with an array of size 8.

@Edit2: in the source code you can see:

 * Weekday strings. For example: "Sunday", "Monday", etc.  An array
 * of 8 strings, indexed by <code>Calendar.SUNDAY</code>,
 * <code>Calendar.MONDAY</code>, etc.
 * The element <code>weekdays[0]</code> is ignored.

So as I said they are simply using Calendar values as indices, that's all.

Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
  • Thanks.But it returns : [, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday], No of days : 8 ? why it returns 8 values or an additional blank value – Prateek Sep 19 '14 at 09:22
  • its you guess but we don't know whats their logic behind doing so.From source code they mention it as : weekdays[0] = ""; // 1-based – Prateek Sep 19 '14 at 09:34
  • @Prateek as I said they simply use ```Calendar``` vals to indes their array and since ```Calendar``` uses 1-based values they have to make a bigger array. – Mateusz Dymczyk Sep 19 '14 at 13:24
3

Java SE 8 and later provides enums:

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Puce
  • 37,247
  • 13
  • 80
  • 152
  • 1
    I am having java SE6 version :( – Prateek Sep 19 '14 at 08:41
  • @Prateek Much of the java.time functionality including [`DayOfWeek`](http://www.threeten.org/threetenbp/apidocs/org/threeten/bp/DayOfWeek.html) is back-ported to Java 6 and Java 7 in the [ThreeTen-Backport](http://www.threeten.org/threetenbp/) project. – Basil Bourque Mar 18 '17 at 05:02
0

Using java.time

The Answer by Puce is correct, but brief. I'll add more detail.

DayOfWeek & Month enums

The java.time classes include DayOfWeek and Month enum classes. An enum means they pre-define several objects. In this case we already have seven objects in DayOfWeek, one for each day of the week. And we have a dozen Month objects already defined for January-December.

EnumSet

Java also provides a highly optimized implementation of Set for collecting enum objects, EnumSet, to use very little memory while executing extremely fast.

If you want just the weekend, you can define a pair of days in a set.

Set<DayOfWeek> weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;

In your case we want all seven days.

Set<DayOfWeek> days = EnumSet.allOf( DayOfWeek.class );

Localize

When you want to see strings for the names of the day, ask. Automatically localize by calling getDisplayName. Specify how long or abbreviated you want the name. Pass a Locale to determine the human language to use in translating the name of the day.

for( DayOfWeek dow : days ) {
    String output = dow.getDisplayName( 
                        TextStyle.FULL , 
                        Locale.CANADA_FRENCH 
                    ) ;
}

You can do all the same stuff for Month.

Set<Month> months = EnumSet.allOf( Month.class );
for( Month month : months ) {
    String output = month.getDisplayName( 
                        TextStyle.FULL , 
                        Locale.CANADA_FRENCH 
                    ) ;
}

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?

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154