Program to show date and time using only Date class methods

The java.util.Date class represents date and time in java. It provides constructors and methods to deal with date and time in java. The java.util.Date class implements Serializable, Cloneable and Comparable interface.

The constructors of java.util.Date class are given below:
  • Date( ) : Creates a date object representing current date and time.
  • Date(long milliseconds) : Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
Some of the methods of Data class are:
  • long getTime( ) : Returns the time represented by this date object.
  • boolean equals(Date date) : Compares current date with given date for equality.
  • void setTime(long time) : Changes the current date and time to given time.
  • String toString( ) : Converts this date into Instant object.

import java.util.Date;

class DateDemo {

 public static void main(String args[]) {
  // Instantiate a Date object
  Date date = new Date();
  // display time and date using toString()
  // Display number of milliseconds since midnight, January 1, 1970 GMT
  long msec = date.getTime();
  System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);
C:\>java DateDemo
Tue Sep 29 19:33:33 IST 2015
Milliseconds since Jan. 1, 1970 GMT = 1443535413446

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative