One of the most important advantages of using Servlets is the ability to use most of the available methods in core Java. This chapter will explain the Date class provided in the java.util package by Java, which encapsulates the current date and time.
\n\nThe Date class supports two constructors. The first constructor initializes an object with the current date and time.
\n\nDate( )
\n\nThe following constructor accepts a parameter that equals the number of milliseconds elapsed since midnight, January 1, 1970.
\n\nDate(long millisec)
\n\nOnce you have a Date object available, you can call any of the following supported methods to use the date:
\n\n| Index | \nMethod & Description | \n
|---|---|
| 1 | \nboolean after(Date date) Returns true if the date contained in the calling Date object is after the date specified by date; otherwise, returns false. | \n
| 2 | \nboolean before(Date date) Returns true if the date contained in the calling Date object is before the date specified by date; otherwise, returns false. | \n
| 3 | \nObject clone( ) Duplicates the calling Date object. | \n
| 4 | \nint compareTo(Date date) Compares the value of the calling object with that of date. Returns 0 if the values are equal. Returns a negative value if the calling object is earlier than date. Returns a positive value if the calling object is later than date. | \n
| 5 | \nint compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. | \n
| 6 | \nboolean equals(Object date) Returns true if the time and date represented by the calling Date object and date are equal; otherwise, returns false. | \n
| 7 | \nlong getTime( ) Returns the number of milliseconds elapsed since January 1, 1970. | \n
| 8 | \nint hashCode( ) Returns a hash code for the calling object. | \n
| 9 | \nvoid setTime(long time) Sets the time and date as specified by time, which represents the number of milliseconds elapsed since midnight, January 1, 1970. | \n
| 10 | \nString toString( ) Converts the calling Date object into a string and returns the result. | \n
It is very easy to get the current date and time in a Java Servlet. You can use a simple Date object's toString() method to output the current date and time, as shown below:
\n\npackage com.tutorial.test;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Date;\nimport javax.servlet.ServletException;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Servlet implementation class CurrentDate\n */\n@WebServlet("/CurrentDate")\npublic class CurrentDate extends HttpServlet {\n private static final long serialVersionUID = 1L;\n\n public CurrentDate() {\n super();\n }\n\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType("text/html;charset=UTF-8");\n PrintWriter out = response.getWriter();\n\n String title = "Displaying Current Date and Time";\n Date date = new Date();\n String docType = "<!DOCTYPE html> n";\n\n out.println(docType + "<html>n" +\n "<head><title>" + title + "</title></head>n" +\n "<body bgcolor="#f0f0f0">n" +\n "<h1 align="center">" + title + "</h1>n" +\n "<h2 align="center">" + date.toString() + "</h2>n" +\n "</body></html>");\n }\n}\n\n\nNow, let us compile the above Servlet and create an appropriate entry in the web.xml file:
\n\n<?xml version="1.0" encoding="UTF-8"?>\n<web-app>\n\n <servlet>\n <servlet-name>CurrentDate</servlet-name>\n <servlet-class>com.tutorial.test.CurrentDate</servlet-class>\n </servlet>\n\n <servlet-mapping>\n <servlet-name>CurrentDate</servlet-name>\n <url-pattern>/TomcatTest/CurrentDate</url-pattern>\n </servlet-mapping>\n\n</web-app>\n\n\nNow call this Servlet using the URL http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:
\n\nTry refreshing the URL http://localhost:8080/TomcatTest/CurrentDate every few seconds, and you will notice a difference in the displayed time.
\n\nAs mentioned above, you can use all available Java methods in a Servlet. If you need to compare two dates, here are the methods:
\n\n- \n
- You can use getTime() to get the number of milliseconds elapsed since midnight, January 1, 1970, for both objects, and then compare these two values. \n
- You can use the methods before(), after(), and equals(). Since the 12th of a month comes before the 18th, for example, new Date(99, 2, 12).before(new Date(99, 2, 18)) returns true. \n
- You can use the compareTo() method, which is defined by the Comparable interface and implemented by Date. \n
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to choose any user-defined date-time formatting pattern.
\n\nLet us modify the above example as follows:
\n\npackage com.tutorial.test;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport javax.servlet.ServletException;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Servlet implementation class CurrentDate\n */\n@WebServlet("/CurrentDate")\npublic class CurrentDate extends HttpServlet {\n private static final long serialVersionUID = 1L;\n\n public CurrentDate() {\n super();\n }\n\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType("text/html;charset=UTF-8");\n PrintWriter out = response.getWriter();\n\n String title = "Displaying Current Date and Time";\n Date dNow = new Date( );\n SimpleDateFormat ft = new SimpleDateFormat ("yyyy.MM.dd hh:mm:ss E a ");\n String docType = "<!DOCTYPE html> n";\n\n out.println(docType + "<html>n" +\n "<head><title>" + title + "</title></head>n" +\n "<body bgcolor="#f0f0f0">n" +\n "<h1 align="center">" + title + "</h1>n" +\n "<h2 align="center">" + ft.format(dNow) + "</h2>n" +\n "</body></html>");\n }\n}\n\n\nCompile the above Servlet again and call it using the URL http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:
\n\nUse event pattern strings to specify the time format. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as follows:
\n\n| Character | \nDescription | \nInstance | \n
|---|---|---|
| G | \nEra Indicator | \nAD | \n
| y | \nFour-digit year | \n2001 | \n
| M | \nMonth of the year | \nJuly or 07 | \n
| d | \nDay of the month | \n10 | \n
| h | \nWith A.M./P.M. Hour (1-based)~12οΌ | \n12 | \n
| H | \nHour of the day (0-based)~23οΌ | \n22 | \n
| m | \nMinute of the hour | \n30 | \n
| s | \nSecond of the minute | \n55 | \n
| S | \nMillisecond | \n234 | \n
| E | \nDay of the week | \nTuesday | \n
| D | \nDay of the year | \n360 | \n
| F | \nWeek of the month | \n2 (second Wed. in July) | \n
| w | \nWeek of the year | \n40 | \n
| W | \nWeek of the month | \n1 | \n
| a | \nA.M./P.M. Flag | \nPM | \n
| k | \nHour of the day (1-based)~24οΌ | \n24 | \n
| K | \nWith A.M./P.M. Hour (0-based)~11οΌ | \n10 | \n
| z | \nTime zone | \nEastern Standard Time | \n
| ' | \nEscape for text | \nDelimiter | \n
| " | \nSingle quote | \n` | \n
For a complete list of available date-handling methods, you can refer to the standard Java documentation.
YouTip