Edward
Edward

Reputation: 91

Dates manipulations in iReport

I have datetime column which has data like: 2013-04-19 23:44:27.357

In iReport I'm using expression new SimpleDateFormat("h:mma").format($F{domain_datetime}) to display only the time.

In the expression above I'd like to say if time greater then 23:59 then instead of displaying time I want to display a day, for example 5 MAR 13, otherwise display a time.

How to do it?

Upvotes: 2

Views: 2381

Answers (2)

drewich
drewich

Reputation: 148

Why don't you do it on the query used to fill up the report or in Java if your are using a JRBeanCollectionDataSource? That way you only need to show a text no matter what is it

Upvotes: 0

Jacob Schoen
Jacob Schoen

Reputation: 14212

If you are are don't care about the information beyond seconds, and simply want to convert anything that would format to 12:00AM the day you could replace your current expression with:

(new SimpleDateFormat("h:mma").format($F{domain_datetime}).equals("12:00AM")) ? 
new SimpleDateFormat("dd MMM yy").format($F{domain_datetime}) : 
new SimpleDateFormat("h:mma").format($F{domain_datetime})

Now this works, but it creates 3 new SimpleDateFormat instances for the expression, when only 2 or needed (I would also be curious to know if it would create 3 new SimpleDateFormat objects for each row, but I don't know if that is the case). So in my eyes this can be improved some.

Create two new Parameters in your report that will be SimpleDateFormat instances. The XML for them should look like:

<parameter name="TIME_FORMAT" class="java.text.SimpleDateFormat" isForPrompting="false">
    <defaultValueExpression><![CDATA[new SimpleDateFormat("h:mma")]]></defaultValueExpression>
</parameter>
<parameter name="DATE_FORMAT" class="java.text.SimpleDateFormat" isForPrompting="false">
    <defaultValueExpression><![CDATA[new SimpleDateFormat("dd MMM yy")]]></defaultValueExpression>
</parameter>

They have default values for the date formatter, and we can reference them in our expression. So now we can rewrite our expression to be:

($P{TIME_FORMAT}.format($F{domain_datetime}).equals("12:00AM")) ? 
$P{DATE_FORMAT}.format($F{domain_datetime}) : 
$P{TIME_FORMAT}.format($F{domain_datetime})

Upvotes: 1

Related Questions