Monday, 10 October 2016

How to work with DatePicker in HTML5 and JSP?

Today we'll look how to work with Datepicker in HTML5 and display the date in different formats in JSP. 

Let us look into one simple example. For this we need one HTML5 web page with one form containing Date picker and one JSP page to parse and format the date.

Now we'll create our HTML page 

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Date Picker Demo</title>
</head>
<body>
<form action="result.jsp" method="post">
Select Date : <input type="date" name="myDate"><br/>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

After creating our HTML page, we'll create our JSP page to get the request from HTML page and process the request.

result.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Result</title>
</head>
<body>
<%

String myDate = request.getParameter("myDate");

out.print("Date without formatting (yyyy-MM-dd): "+myDate);

%>
<br/>
<%

java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date dt = df.parse(myDate);

out.println("Parsing String into Date (yyyy-MM-dd) : "+dt);

%>
<br/>
<%

java.text.DateFormat dateFmt1 = new java.text.SimpleDateFormat("MM-dd-yyyy");
String date1 = dateFmt1.format(dt);

out.println("Formatting Date into String (MM-dd-yyyy) : "+date1);

%>
<br/>
<%

java.text.DateFormat dateFmt2 = new java.text.SimpleDateFormat("dd/MM/yyyy");
String date2 = dateFmt2.format(dt);

out.println("Formatting Date into String (dd/MM/yyyy) : "+date2);

%>
<br/>
<%

java.text.DateFormat dateFmt3 = new java.text.SimpleDateFormat("dd-MM-yyyy");
String date3 = dateFmt3.format(dt);

out.println("Formatting Date into String (dd-MM-yyyy) : "+date3);

%>
<br/>
<%

java.text.DateFormat dateFmt4 = new java.text.SimpleDateFormat("dd-MMM-yyyy");
String date4 = dateFmt4.format(dt);

out.println("Formatting Date into String (dd-MMM-yyyy) : "+date4);
%>
</body>

</html>


Now let us look into the output -

Output -

Date without formatting (yyyy-MM-dd): 2016-10-12
Parsing String into Date (yyyy-MM-dd) : Wed Oct 12 00:00:00 IST 2016
Formatting Date into String (MM-dd-yyyy) : 10-12-2016
Formatting Date into String (dd/MM/yyyy) : 12/10/2016
Formatting Date into String (dd-MM-yyyy) : 12-10-2016
Formatting Date into String (dd-MMM-yyyy) : 12-Oct-2016


In the above example, first we get the value of myDate parameter and store into one String myDate. To display the selected date first we parsed the String into Date dt using parse() method and change the Date dt into different formats using format() method.


No comments:

Post a Comment