Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a calendar in a constructor

If I do this:

new Estimacao("Aarão","Affenpinscher","Abóbora",new GregorianCalendar(1999,7,26),0),

Everything works as as expected. But if i do this:

new Estimacao("Aarão","Affenpinscher","Abóbora",new Calendar(1999,7,26),0),

It can be done. As far as I know. We have to initialize calendar like this:

Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, 1999);
date.set(Calendar.MONTH, 7);
date.set(Calendar.DAY_OF_MONTH, 26);

The thing I want to know is if it's possible to use Calendar, and achieve the same as GregorianCalendar, when creating and initializing the object new Estimacao as above.

like image 412
Favolas Avatar asked Dec 22 '11 14:12

Favolas


People also ask

What is calendar getInstance () in Java?

The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Syntax: public static Calendar getInstance() Parameters: The method does not take any parameters. Return Value: The method returns the calendar.

Can you format calendar class Java?

The DateFormat class in Java is used for formatting dates. A specified date can be formatted into the Data/Time string. For example, a date can be formatted into: mm/dd/yyyy.

Which Java package is used for date calendar?

Calendar class in Java is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc.


1 Answers

Calendar is an Abstract class, so you can't create an instance of it. When you call getInstance it actually returns a new GregorianCalendar instance. So it is the same as your first example.

So I guess the question is, why do you want to call new Calendar instead of new GregorianCalendar? If it is just so that you can hide the implementation you are using then I would either just do what you have already done to initialise a Calendar. Or create a single method that takes the same parameters and hides the calls to the Calendar class, e.g.

public Calendar getCalendar(int day, int month, int year) {
    Calendar date = Calendar.getInstance();
    date.set(Calendar.YEAR, year);

    // We will have to increment the month field by 1

    date.set(Calendar.MONTH, month+1);

    // As the month indexing starts with 0

    date.set(Calendar.DAY_OF_MONTH, day);

    return date;
}
like image 67
DaveJohnston Avatar answered Oct 12 '22 04:10

DaveJohnston