Date: 2012feb26
Language: Java
Level: beginner
Q. Java: Get values from the GregorianCalendar or Calendar class
A.
import java.util.Calendar;
Calendar mycal = Calendar.getInstance(); // The current date/time
int year = mycal.get(Calendar.YEAR); // eg 2035
int month1 = mycal.get(Calendar.MONTH) + 1; // Calendar.MONTH is zero-based
int jday = mycal.get(Calendar.DAY_OF_YEAR);
int mday = mycal.get(Calendar.DAY_OF_MONTH);
int wday = mycal.get(Calendar.DAY_OF_WEEK);
int hour24 = mycal.get(Calendar.HOUR_OF_DAY);
int hour12 = mycal.get(Calendar.HOUR);
int minute = mycal.get(Calendar.MINUTE);
int second = mycal.get(Calendar.SECOND);
int milli = mycal.get(Calendar.MILLISECOND);
You could make a class for this:
import java.util.Calendar;
import java.util.GregorianCalendar;
class OneCal extends GregorianCalendar {
int getYear() { return get(Calendar.YEAR); }
int getMonth1() { return get(Calendar.MONTH) + 1; } // Gives 1-based month
int getJulianDay() { return get(Calendar.DAY_OF_YEAR); }
int getDayOfMonth() { return get(Calendar.DAY_OF_MONTH); }
int getDayOfWeek() { return get(Calendar.DAY_OF_WEEK); }
int getHour24() { return get(Calendar.HOUR_OF_DAY); }
int getHour12() { return get(Calendar.HOUR); }
int getMinute() { return get(Calendar.MINUTE); }
int getSecond() { return get(Calendar.SECOND); }
int getMilli() { return get(Calendar.MILLISECOND); }
String getDate() { return String.format("%04d-%02d-%02d", getYear(), getMonth1(), getDayOfMonth()); }
String getTime() { return String.format("%02d:%02d:%02d", getHour24(), getMinute(), getSecond()); }
}