Thursday, 20 December 2012

Formatting the Date

  1. <%@page import="java.util.*" %>
  2. <%@ page import="java.text.*" %>
  3. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  4. pageEncoding="ISO-8859-1"%>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <title>Displaying Dates</title>
  9. </head>
  10. <body>
  11. <h3>Displaying Today's date in different formats:</h3>
  12. <%!
  13. Date today=new Date();
  14. DateFormat formatFull=DateFormat.getDateInstance(DateFormat.FULL);
  15. DateFormat formatLong=DateFormat.getDateInstance(DateFormat.LONG);
  16. DateFormat formatMedium=DateFormat.getDateInstance(DateFormat.MEDIUM);
  17. DateFormat formatShort=DateFormat.getDateInstance(DateFormat.SHORT);
  18. %>
  19. <p>
  20. Full Format: <%=formatFull.format(today) %>
  21. <br>
  22. Long Format: <%=formatLong.format(today) %>
  23. <br>
  24. Medium Format: <%=formatMedium.format(today) %>
  25. <br>
  26. Short Format: <%=formatShort.format(today) %>
  27. </body>
  28. </html>

Description:


  • Use the import page directive to import the java.text.package.
  • Create a Date object.
  • Create a Date Format object by calling the getDateInstance method and passing DateFormat.FULL as a parameter.
  • Create a Date Format object by calling the getDateInstance method and passing DateFormat.LONG as a parameter.
  • Create a Date Format object by calling the getDateInstance method and passing DateFormat.MEDIUM as a parameter.
  • Create a Date Format object by calling the getDateInstance method and passing DateFormat.SHORT as a parameter.
  • Pass the current date as a parameter to the format method of the FormatFull object.This will display the full date, for example: 21 December 2012.
  • Pass the current date as a parameter to the format method of the FormatLong object.This will display the long date, for example:12/21 /2012.
  • Pass the current date as a parameter to the format method of the FormatMedium object.This will display the medium date, for example:Friday, 21 December 2012.
  • Pass the current date as a parameter to the format method of the FormatShort object.This will display the short date, for example:12/21 /12.

******************************OUTPUT******************************************

Displaying Today's date in different formats:

Full Format: Friday, December 21, 2012
Long Format: December 21, 2012
Medium Format: Dec 21, 2012
Short Format: 12/21/12  


********************************************************************************

No comments:

Post a Comment