In this tutorial we will see how to get current date, day, month, year, day of week, day of month and day of year in java.
import java.util.Calendar; import java.util.Date; import java.util.TimeZone; class Example { public static void main(String args[]) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); //getTime() returns the current date in default time zone Date date = calendar.getTime(); int day = calendar.get(Calendar.DATE); //Note: +1 the month for current month int month = calendar.get(Calendar.MONTH) + 1; int year = calendar.get(Calendar.YEAR); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); System.out.println("Current Date is: " + date); System.out.println("Current Day is:: " + day); System.out.println("Current Month is:: " + month); System.out.println("Current Year is: " + year); System.out.println("Current Day of Week is: " + dayOfWeek); System.out.println("Current Day of Month is: " + dayOfMonth); System.out.println("Current Day of Year is: " + dayOfYear); } }
Output:
Current Date is: Wed Jan 08 20:30:26 IST 2014 Current Day is:: 8 Current Month is:: 1 Current Year is: 2014 Current Day of Week is: 4 Current Day of Month is: 8 Current Day of Year is: 8
In the above example we have fetched the data of local timezone (note: we have used TimeZone.getDefault()
in the first statement of the program. However it is also possible to get these details for another TimeZone.
Here is how to do it:
Calendar cal = Calendar.getInstance(TimeZone.getDefault()); //change the timezone: Provide the TimeZone Id as parameter cal.setTimeZone(TimeZone.getTimeZone("Europe/Athens")); //get the details in new time zone System.out.println(cal.get(Calendar.HOUR_OF_DAY)); System.out.println(cal.get(Calendar.WEEK_OF_MONTH)); System.out.println(cal.get(Calendar.WEEK_OF_YEAR)); ...
Here Europe/Athens
is the Id of a TimeZone. In order to know the all the Ids, run the following code. It would give you all existing Ids which you can use in your program:
for (String string : TimeZone.getAvailableIDs()) { System.out.println(string); }
Output would be like:
Etc/GMT+12 Etc/GMT+11 Pacific/Midway Pacific/Niue Pacific/Pago_Pago Pacific/Samoa US/Samoa America/Adak America/Atka Etc/GMT+10 HST .... ...
References:
Leave a Reply