Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set all months to a list in java [duplicate]

Tags:

java

calendar

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!

like image 762
Imesh Chandrasiri Avatar asked May 30 '13 04:05

Imesh Chandrasiri


2 Answers

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

like image 77
PSR Avatar answered Oct 01 '22 09:10

PSR


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.

like image 43
Zong Avatar answered Oct 01 '22 07:10

Zong