Java Programing laungage

java.util Projects

java.util Project 1

Getting the Current Time

In This page of the tutorials, we shows the way of getting the current system time. Through the given Example we can get the current time in the proper format (Hour:Minute:Second AM/PM). This program shows the current time by using the some methods of the Calendar class. These are as follow.

Previous Home Next
Code Description

Calendar

This class is used to help us to convert a date format object into the integer fields like YEAR, MONTH, HOUR, MINUTE, SECOND etc.

Calendar.get(Calendar.MINUTE)

This method gives us the minute value from the current time and MINUTE is the predefined field of the Calendar class which returns the integer value i.e. the minute value of the current time.

Calendar.AM_PM

This field of the Calendar class is used to return the integer value 1 and 0, if the current time is in the PM then it return the 1 otherwise it returns 0 value.

Example


package r4r;
import java.util.*;
public class correnttimetest {
public static void main(String[] args){
Calendar cal = new GregorianCalendar();
String am_pm;
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
if(cal.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
System.out.println("Current Time is: " + hour + ":" 
 + minute + ":" + second + " " + am_pm);
}
}

Previous Home Next