I'm trying to get all 12 months into a String list in java. How can I do this using the java.util calender. I've used the following code to build a year list! now I want is to build a month list for the 12 months.
protected String getYears(){
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 3);
int futureYear = cal.get(Calendar.YEAR);
List<String> years = new ArrayList<String>();
for(int i = -2 ; i < 1 ; i++){
if(i != 0){
cal = Calendar.getInstance();
cal.add(Calendar.YEAR,i);
years.add(Integer.toString(cal.get(Calendar.YEAR)));
}else if(currentYear != futureYear){
years.add(Integer.toString(currentYear));
years.add(Integer.toString(futureYear));
}else if(currentYear == futureYear){
years.add(Integer.toString(currentYear));
}
}
HTMLOptionBuilder ob = new HTMLOptionBuilder(false);
for(int i = 0; i < years.size(); i++){
if(years.get(i).equals(currentYear)){
ob.addOption(years.get(i), years.get(i), true, true);
}else{
ob.addOption(years.get(i), years.get(i));
}
}
return ob.getHTML();
}
please help me! thank you!
try this
import java.text.DateFormatSymbols;
public class Main {
public static void main(String[] args) {
List<String> monthsList = new ArrayList<String>();
String[] months = new DateFormatSymbols().getMonths();
for (int i = 0; i < months.length; i++) {
String month = months[i];
System.out.println("month = " + month);
monthsList .add(months[i]);
}
DateFormatSymbols
This uses 100 less characters than PSR's solution. :)
List<String> months = Arrays.asList("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
Also I think this is more immediately obvious, but doesn't work if you want locales or other weird things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With