Dave's Brain

Browse - Programming Tips - How do you get() values from the Calendar class?

Date: 2012feb26
Language: Java
Level: beginner

Q.  How do you get() values from the Calendar class?

A.
import java.util.Calendar; Calendar mycal = Calendar.getInstance(); // The current date/time int year = mycal.get(Calendar.YEAR); // eg 2035 int month = mycal.get(Calendar.MONTH) + 1; // 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 getMonth() { return get(Calendar.MONTH) + 1; } 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(), getMonth(), getDayOfMonth()); } String getTime() { return String.format("%02d:%02d:%02d", getHour24(), getMinute(), getSecond()); } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.