One of the most important advantages of using Servlet is that you can use most of the methods available in the core Java. This chapter will explain what Java provides
java.util
in the bag
Date
class, which encapsulates the current date and time.
Date
class supports two constructors. The first constructor initializes the object for the current date and time.
Date( )
The following constructor takes an argument equal to the number of milliseconds that have elapsed since midnight on January 1, 1970.
Date(long millisec)
Once you have an available Date object, you can call any of the following supported methods to use the date:
Serial number | Method & description |
|---|---|
1 | Boolean after (Date date) returns true if the date contained in the called Date object is after the date specified by date, otherwise returns false. |
2 | Boolean before (Date date) returns true if the date contained in the called Date object is before the date specified by date, otherwise returns false. |
3 | Object clone () calls the Date object repeatedly. |
4 | Int compareTo (Date date) compares the value of the calling object with the value of date. Returns 0 if the two values are equal. Returns a negative value if the calling object is before date. If the calling object is after date, a positive value is returned. |
5 | Int compareTo (Object obj) if obj is a Date class, the operation is equivalent to compareTo (Date). Otherwise, it throws a ClassCastException. |
6 | Boolean equals (Object date) returns true if the called Date object containsthe same time and date as specified by date, otherwise it returns false. |
7 | Long getTime () returns the number of milliseconds that have elapsed since January 1, 1970. |
8 | Int hashCode () returns a hash code for the calling object. |
9 | Void setTime (long time) sets the time and date specified by time, which represents the elapsed time in milliseconds since midnight on January 1, 1970. |
10 | The Date object called by the String toString () transformation is a string and returns the result. It is very easy to get the current date and time in Java Servlet. You can use a simple Now, let’s compile the above Servlet and set it in the The Servlet is then called by accessing the http://localhost:8080/TomcatTest/CurrentDate . This will produce the following results: Try to refresh URL http://localhost:8080/TomcatTest/CurrentDate , and you will notice the difference in display time every few seconds. As mentioned above, you can use all the available Java methods in Servlet. If you need to compare two dates, here is the method: You can use the You can use the method You can use the Let’s modify the above example as follows: Compile the above Servlet again, and then call the Servlet by accessing http://localhost:8080/TomcatTest/CurrentDate . This will produce the following results: Use the event pattern string to specify the time format. In this mode, all ASCII letters are retained as pattern letters, which are defined as follows: |