Monday, January 30, 2006

Adding a Few Hours to a Java Date (in JSTL)

I had to add 2 or 12 hours to a date stored as a string. Use the fmt tag library. It contains parseDate, which takes a String and returns a Java Date object. formatDate prints out a Date object as a string. I added the time by manipulating the time zone of each date as follows:

<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

...

<fmt:parsedate value="${BEGIN_DATE}" var="BEGINPLUS12" pattern="MM/dd/yyyy HH:mm"
timezone="GMT+00">

<fmt:formatdate value="${BEGINPLUS12}" type="both" pattern="MM/dd/yyyy HH:mm"
timezone="GMT+12">
<%-- add 12 hours by changing time zone --%>


The type="both" in the formatDate keeps it from discarding the time information.

Used the following two pages to figure this out:
formatDate, parseDate: http://www-128.ibm.com/developerworks/java/library/j-jstl0415/
Java Time Zones: http://java.sun.com/j2se/1.4.2/docs/api/java/util/TimeZone.html

No comments:

Labels

Blog Archive

Contributors