Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

date arithmetic

 
Dan Murphy
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64830
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Dan Murphy
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64830
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64830
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic