Servlets - Handling Date


One of the most critical points of interest of utilizing Servlet is that you can utilize the vast majority of the strategies accessible in center Java. This instructional exercise would take you through Java gave Date class which is accessible in java.util bundle, this class embodies the present date and time.

The Date class bolsters two constructors. The main constructor instates the item with the present date and time.

Date( ) 

The following constructor acknowledges one contention that parallels the quantity of milliseconds that have passed since midnight, January 1, 1970

Date(long millisec) 

Once you have a Date object accessible, you can call any of the accompanying help strategies to play with dates −

Sr.No. Methods & Description
1

boolean after(Date date)

Returns genuine if the summoning Date object contains a date that is later than the one indicated by date, else, it returns false.

2

boolean before(Date date)

Returns genuine if the conjuring Date object contains a date that is sooner than the one determined by date, else, it returns false.

3

Object clone( )

Duplicates the conjuring Date object.

4

int compareTo(Date date)

Compares the estimation of the conjuring object with that of date. Returns 0 if the qualities are equivalent. Returns a negative esteem if the summoning object is sooner than date. Returns a positive esteem if the conjuring object is later than date.

5

int compareTo(Object obj)

Operates indistinguishably to compareTo(Date) if obj is of class Date. Else, it tosses a ClassCastException.

6

boolean equals(Object date)

Returns genuine if the summoning Date object contains indistinguishable time and date from the one determined by date, else, it returns false.

7

long getTime( )

Returns the quantity of milliseconds that have passed since January 1, 1970.

8

int hashCode( )

Returns a hash code for the summoning object.

9

void setTime(long time)

Sets the time and date as indicated by time, which speaks to a slipped by time in milliseconds from midnight, January 1, 1970.

10

String toString( )

Converts the conjuring Date object into a string and returns the result.

Getting Current Date & Time

This is anything but difficult to get current date and time in Java Servlet. You can utilize a basic Date object with toString() strategy to print current date and time as pursues −

//Import required java libraries

import java.io.*; 

import java.util.Date; 

import javax.servlet.*; 

import javax.servlet.http.*; 

//Extend HttpServlet class 

public class CurrentDate extends HttpServlet { 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

//Set reaction content type 

response.setContentType("text/html"); 

PrintWriter out = response.getWriter(); 

String title = "Display Current Date & Time"; 

Date date = new Date(); 

String docType = "<!doctype html open \"-/w3c//dtd html 4.0 " + "transitional//en\">\n"; 

out.println(docType + 

"<html>\n" + 

"<head><title>" + title + "</title></head>\n" + 

"<body bgcolor = \"#f0f0f0\">\n" + 

"<h1 adjust = \"center\">" + title + "</h1>\n" + 

"<h2 adjust = \"center\">" + date.toString() + "</h2>\n" + 

"</body> 

</html>" 

); 

} 

}

Now let us aggregate above servlet and make proper sections in web.xml and after that call this servlet utilizing URL http://localhost:8080/CurrentDate. This would create following outcome −

Display Current Date & Time

Mon Jun 21 21:46:49 GMT+04:00 2010

Try to invigorate URL http://localhost:8080/CurrentDate and you would discover contrast in seconds each time you would refresh.

Date Comparison

As I referenced above you can utilize all the accessible Java strategies in your Servlet. In the event that you have to look at two dates, following are the strategies −

  • You can utilize getTime( ) to get the quantity of milliseconds that have slipped by since midnight, January 1, 1970, for the two articles and after that look at these two values.

  • You can utilize the techniques previously( ), after( ), and breaks even with( ). Since the twelfth of the month precedes the eighteenth, for instance, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.

  • You can utilize the compareTo( ) technique, which is characterized by the Comparable interface and executed by Date.

Date Formatting utilizing SimpleDateFormat

SimpleDateFormat is a solid class for designing and parsing dates in a localesensitive way. SimpleDateFormat enables you to begin by picking any client characterized designs for date-time organizing.

Let us change above model as pursues −

//Import required java libraries 

import java.io.*; 

import java.text.*; 

import java.util.Date; 

import javax.servlet.*; 

import javax.servlet.http.*; 

//Extend HttpServlet class 

public class CurrentDate extends HttpServlet { 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

//Set reaction content type 

response.setContentType("text/html"); 

PrintWriter out = response.getWriter(); 

String title = "Display Current Date & Time"; 

Date dNow = new Date( ); 

SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); 

String docType = "<!doctype html open \"-/w3c//dtd html 4.0 " + "transitional//en\">\n"; 

out.println(docType + 

"<html>\n" + 

"<head><title>" + title + "</title></head>\n" + 

"<body bgcolor = \"#f0f0f0\">\n" + 

"<h1 adjust = \"center\">" + title + "</h1>\n" + 

"<h2 adjust = \"center\">" + ft.format(dNow) + "</h2>\n" + 

"</body> 

</html>" 

); 

} 

}

Compile above servlet indeed and after that call this servlet utilizing URL http://localhost:8080/CurrentDate. This would create following outcome −

Display Current Date & Time

Mon 2019.02.21 at 10:06:44 PM GMT+04:00

Simple DateFormat Format Codes

To determine the time design utilize a period design string. In this example, all ASCII letters are saved as example letters, which are characterized as the accompanying −

Character Description Example
G Era designator AD
y Year in four digits 2001
M Month in year July or 07
d Day in month 10
h Hour in A.M./P.M. (1~12) 12
H Hour in day (0~23) 22
m Minute in hour 30
s Second in minute 55
S Millisecond 234
E Day in week Tuesday
D Day in year 360
F Day of week in month 2 (second Wed. in July)
w Week in year 40
W Week in month 1
a A.M./P.M. marker PM
k Hour in day (1~24) 24
K Hour in A.M./P.M. (0~11) 10
z Time zone Eastern Standard Time
' Escape for text Delimiter
" Single quote '

For a total rundown of steady accessible strategies to control date, you can allude to standard Java documentation.







© Javacodegeeks 2018 -
All Right Reserved and you agree to have read and accepted our term and condition.

Python 3