368
In this example we will show how to get the current date and time using the Calendar class in Java
We then use various fields to show the Day of the week, Day of the year, hour, minute and seconds amongst others
Example
import java.util.*; public class JavaApplication1 { public static void main(String[] args) { Calendar myCalendar = Calendar.getInstance(); System.out.println("Day of week : " + myCalendar.get(Calendar.DAY_OF_WEEK)); System.out.println("Day of year : " + myCalendar.get(Calendar.DAY_OF_YEAR)); System.out.println("Week in Month : " + myCalendar.get(Calendar.WEEK_OF_MONTH)); System.out.println("Week in Year : " + myCalendar.get(Calendar.WEEK_OF_YEAR)); System.out.println("Day of Week in Month : " + myCalendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); System.out.println("Hour : " + myCalendar.get(Calendar.HOUR)); System.out.println("Minute : " + myCalendar.get(Calendar.MINUTE)); System.out.println("Second : " + myCalendar.get(Calendar.SECOND)); System.out.println("AM or PM : " + myCalendar.get(Calendar.AM_PM)); System.out.println("Hour (24-hour clock) : " + myCalendar.get(Calendar.HOUR_OF_DAY)); } }
When run you will see something similar to this
run: Day of week : 1 Day of year : 107 Week in Month : 2 Week in Year : 15 Day of Week in Month : 3 Hour : 10 Minute : 26 Second : 8 AM or PM : 0 Hour (24-hour clock) : 10