FBwall
FBwall

Reputation: 1653

Custom gregoriancalendar month

How do I instantiate the calendar depending on the input of the user? I've tried:

Calendar cal = new GregorianCalendar(2011, Calendar.t.getMonth(month), 1);

But didn't do the trick.

import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Scanner;

public class Test {
    public static void main(String[] args){
        Test t = new Test();
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a month: ");
        String month = sc.next();

        Calendar cal = new GregorianCalendar(2011, Calendar.JANUARY, 1);

        int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.print("There are "+days+" days in "+month+".");
    }
    private String getMonth(String month){
        return month;
    }
}

Or maybe a more practical way of doing it? Thanks.

Upvotes: 1

Views: 3120

Answers (4)

jglatre
jglatre

Reputation: 953

GregorianCalendar is not meant to be instantiated directly (read the javadocs), use Calendar.getInstance() instead, and assign values with set(int...) methods.

Upvotes: 0

Raveline
Raveline

Reputation: 2678

For every enum, Java has a valueOf(String) static function, that convert a String to the proper enum. Unfortunately, the constants of the Calendar class such as Calendar.JANUARY are constants and not enum. The best for you could be to build an enum with name of months, connect those months to the Calendar constants, and then, after puting to uppercase the input of the user, use the valueOf function.

With code :

public enum Months {

    JANUARY (0),
    FEBRUARY (1),
    MARS (2) // and so on

    private int value;

    test(int value){
        this.value = value;
    }
}

And in your class, have a function like this one :

private int monthFromString(String userInputMonth) {
   return Months.valueOf(userInputMonth);
}

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117675

You need to add one to the month since it starts from 0 not 1:

int month = sc.nextInt();
Calendar cal = new GregorianCalendar(2011, month + 1, 1);

or if you want the user to insert a String not a numerical value, then you can do something like:

String month = sc.nextLine();
int iMonth = -1;
if(month.equalsIgnoreCase("January"))  iMonth = 0;
else if(month.equalsIgnoreCase("February")) iMonth = 1;
// and so on ...
Calendar cal = new GregorianCalendar(2011, iMonth, 1);

Upvotes: 2

nowaq
nowaq

Reputation: 2748

Use Joda Time instead of native Java GregorianCalendar. Much, much better!

 // From Joda Time documentatio
 // setup date object for midday on Christmas 2004
 Chronology chrono = GregorianChronology.getInstance();
 DateTime dt = new DateTime(2004, 12, 25, 12, 0, 0, 0, chrono);

Upvotes: 1

Related Questions