In: Computer Science
(Using Date Class) The following UML Class Diagram describes the java Date class:
java.util.Date
+Date()
+Date(elapseTime: long)
+toString(): String
+getTime(): long
+setTime(elapseTime: long): void
Constructs a Date object for the current time.
Constructs a Date object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
Returns a string representing the date and time.
Returns the number of milliseconds since January 1,
1970, GMT.
Sets a new elapse time in the object.
The + sign indicates
public modifer
Using this class, display the current time.
Explaination:
a.The below code creates a class dateAndTime and has used the
library java.util.Date to display time and date.
b.Explaination of every function is mentioned in the form of
comment in below code.
c.As only current time is asked so if you have to display only time
or any specific format of date and time you can use
SimpleDateFormat, It is totally optional.
d.Using only date.toString() will display system's current date and
time in the format given in output section below.
e.The below code shows output of all other functions mentioned in
the above question.
dateAndTime.java
import java.util.*; // class having access to Date class
methods
import java.text.SimpleDateFormat;
public class dateAndTime
{
public static void main(String[] args)
{
Date mydate = new Date();
Date d2 = new Date(2323223232L);
// Displaying the current date and time.Returns a string
representing the date and time.
System.out.println("Current Date & Time : "+
mydate.toString());
//Display date and time is particular format.Here it displys only
time.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("Current Time : "+sdf.format(mydate));
//Constructs a Date object for a given time in milliseconds
elapsed
//since January 1, 1970,GMT.
System.out.println("Date object elapsed since January 1, 1970,
GMT."+ d2 );
//Returns the number of milliseconds since January 1,1970,
GMT.
long count = mydate.getTime();
System.out.println("Milliseconds of mydate : " + count);
// Is used to set time by milliseconds. Adds 15680
// milliseconds to January 1, 1970 to get new time.
mydate.setTime(15680);
System.out.println("Time after setting: " +
mydate.toString());
}
}
Output: