wood burning stoves 2.0*
The moose likes JSP and the fly likes date arithmetic Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » JSP
Bookmark "date arithmetic" Watch "date arithmetic" New topic
Author

date arithmetic

Dan Murphy
Ranch Hand

Joined: Mar 29, 2005
Posts: 126
Hi,

In my JSP, I have a request-scoped attribute 'myDate' which is of type java.util.Date. I need to get the index of this month's date and am using the following code:

<fmt:formatDate pattern="MM" value="${myDate}"/>

However it appears that the month index returned is 1-based (January = 1), which is very surprising, as they are 0-based in java.util.Calendar. Is there any way that I can get the index of the month and subtract 1 from it, without using scriptlet code?

Thanks in Advance,
Dan
[ March 19, 2008: Message edited by: Dan Murphy ]

SCJP, SCJD, SCWCD
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60782
    
  65

Originally posted by Dan Murphy:
However it appears that the month index returned is 1-based (January = 1), which is very surprising...
Shouldn't be. <fmt:dateFormat> simply uses java.text.SimpleDateFormat to format dates.

Hint: how could you create a scoped variable from this data that could then be used in an arithmetic expression?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Dan Murphy
Ranch Hand

Joined: Mar 29, 2005
Posts: 126
Hint: how could you create a scoped variable from this data that could then be used in an arithmetic expression?


Thanks for the reply. I know that in EL I can do arithmetic like this:

${10 - 1}

But in my case I want to subtract 1 from the result returned by

<fmt:formatDate pattern="MM" value="${myDate}"/>

So I need to do something like:

${<fmt:formatDate pattern="MM" value="${myDate}"/> - 1}

But of course this is completely invalid syntax. Any chance of another hint? ;)
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60782
    
  65

If you could somehow place the month value into a scoped variable, you could then do ${monthIndex - 1}

Have you explored the <fmt:formatDate> tag thoroughly?
Dan Murphy
Ranch Hand

Joined: Mar 29, 2005
Posts: 126
Thanks for the tip, I finally figured it out:



BTW, the fmt:formatDate does use 1-based indices. I wrote this minimal test:



And it prints:

The month is:
03
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60782
    
  65

Originally posted by Dan Murphy:
BTW, the fmt:formatDate does use 1-based indices.
Yes, I never said it doesn't. I said you shouldn't have been surprised at that.
 
Consider Paul's rocket mass heater.
 
subject: date arithmetic
 
Similar Threads
What is "this" keyword?
Handling Dates in JSP + Beans
oracle DATE
using calendar as a date type
date or calendar object creation