Pr.Pg Next Pg

Handling Date tutorials

  • One of the most important advantages of using Servlet is that you can use most of the methods available in Java. 

  • In this lesson we will use Date class available in a java.util package, this class encapsulates the current date and time.

  • It is very easy to display current date and time on our browser.

  • There are two constructors supported by Date class as below:

    1. Date(): This constructor initializes the object with the current date and time.

    2. Date(long millisec): This constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970

  • Below is the list of Date object methods with description:






boolean after(Date date)

Checks whether this date comes after the specified date.


boolean before(Date date)

Checks whether this date comes before the specified date.


Object clone( )

Duplicates the invoking Date object.


int compareTo(Date date)

Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date.


int compareTo(Object obj)

Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.


boolean equals(Object date)

Compares this object against the specified object.


long getTime( )

Returns the time in milliseconds since the epoch. January 1,1970


int hashCode( )

Returns a hash code for the invoking object.


void setTime(long time)

Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970


String toString( )

Converts a date to a String, using the UNIX ctime conventions.



Example: Servlet program to get current date and time

Sam Sir

//Program name Currentdatetime

// Program to get current date and time


import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Currentdatetime extends HttpServlet


public void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException


PrintWriter pw = response.getWriter();

Date today = new Date();

pw.println(<html>+<body><h1>Today Date is</h1>);

pw.println(<b>+ today+</b></body>+ </html>);




Date and Time in Servlets

Pr.Pg border                                              Next Pg