Link to home
Start Free TrialLog in
Avatar of tagomtech
tagomtechFlag for United States of America

asked on

how to use .getdayofweek

I am trying to format a report that groups the data together by week - with each Sunday being the begining of a new week.

I am thinking that i can use the the following code - just not sure how to set it up in iReports

DateFormatSymbols dfs = new DateFormatSymbols();
    String weekdays[] = dfs.getWeekdays()

any suggestions
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

This is a bit non-specific. The code you posted could be used as the basis of a display, but it's not clear how you'd integrate...
You can use

java.util.Dtae d = new java.util.Date();
 SimpleDateFormat f = new SimpleDtaeFormat("EEE");
String day = f.format(d);
Avatar of tagomtech

ASKER

and that will give me every sunday between date ranges - now to just get it to work inside iReports!

This will give you Strings in the form "Mon", "Tue", etc.

Then you can ue them to sort your array of dates by day of the week
If the range is not that long I'd start from the first day of you range
and scan all of them

java.util.Date d0 = beginDate;

java.util.Date d1 = endDate;
java.util.Date d = d0;

long lms = 24L*60L*3600L*1000L;
 SimpleDateFormat f = new SimpleDtaeFormat("EEE");

ArrayList al = new ArrayList();
while(d.before(d1)){
if(f.format(d).equals("Sun"))al.add(d);
d = new java.util.Date(d.getTime() + lms);


}

There you go. your ArrayList will have all Sundays.

This is porobably noty the most elegant but reliable old-fashioned way
of doing it
@CEHJ That is because I am just out of my element with iReports...and tier documentation leaves much much to be desired! so let me be a little more specific:
My stored procedure passes a startDate and endDate to iReports - I can not change the stored procedure -

classes that i have imported into iReports
java.util.Date
org.apache.commons.lang.time.*
java.util.Calendar

I need to list all data that I am pulling based on week of (starting each sunday)
If I can get that to populate from the pulled data then I am golden on the rest.
I have searched and searched the jasper and ireports sites, have posted to their help area and get ZERO response....hence why I keep coming back to you guys.
Of course in the code above instead of using SimpleDateFormat
you can just use
d.getDay() and check if it is equal to zero - means sunday:

java.util.Date d0 = beginDate;

java.util.Date d1 = endDate;
java.util.Date d = d0;

long lms = 24L*60L*3600L*1000L;

ArrayList al = new ArrayList();
while(d.before(d1)){
if(d.getDay() == 0)al.add(d);
d = new java.util.Date(d.getTime() + lms);


}


ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Okay, here is a little more data and digging that I have found...might can help you show me how to use the expression box better
When drilling down in the last report I had to create a variable for each step
each one of these were done as an individual variable and in an new variable expressions window - img included.
$F{Crew Filled}.getTime() - $F{Call Started}.getTime() response time in milliseconds
($V{responsetime_mls}/1000) response time converted to seconds
$V{secondsResponseTime}.doubleValue() seconds to double
($V{seconds2Double}/60) to figure the average divided by 60 to give decimal output (1.89...you might remember this form the last report!)


so for the date I would think I would need a new window for
new cal.getDay() where day is 0
that would give me the first piece I need to group the data by just not sure how to pull out that one piece of code from the samples i have seen.


If you have anywhere say object "d"  of type java.util.Date then just d.getDay() will be egaul to zero for Sunday - that should probably be
the simplest way. As you see getTime() is time in milliseconds, then
one assumption could be that all these objects are of java.util.Date
perhaps you may want to check $F{Call Started}.getDay()  - ?
I am trying this
new Calendar($F{Call Started}.getfirstdayofweek())
as this would also give me the first day of the week - did not work (thought was i need to get the first day of each week between the two report time periods

I have tried the $F{Call Started}.getDay()
new Date($F{Call Started}.getDay()) this returns the date 12/31/69 6 pm
I know we are on the right track just need to get the returns correct
below are a few formatted pieced of code I found in some of the sample reports....not sure if it will help -



($V{CityyNumber} != null)?(new Integer($V{CityyNumber}.intValue() + 1)):(new Integer(1))

new Date($F{start_year}.intValue() - 1900, $F{start_month}.intValue(), 1)

new Integer($V{TotalLength_1}.intValue()/$V{Count_1}.intValue())

"  " + String.valueOf($V{CityyNumber}) + ". " + $F{billing_address_city}+ ", " + $F{billing_address_country}

$F{close_month_name}+ ", " + $F{close_year}


ooops here is the expression box which allows me to put code into iReports

formatting-windo.JPG
Try the following (as you need a Calendar) then examine the fields
new Calendar().setTime($F{Call Started}).xxxxxx

Open in new window

Sorry
new java.util.GregorianCalendar().setTime($F{Call Started}).xxxxxx

Open in new window

@cehj errors
cannon instantiate the type calendar and xxxxxxxx cannon be resolved or is not a field
okay, I imported the java.util.GregorianCalendar in the program
I then placed the code exactly as you have it in the expression box and this is the error i get
xxxxxxxx can not be resolved or is not a field

I didn't mean literally to type a row of xxx ;) That's intended for the field or method you want
LOL, I know, that was a dur ta dur....just very frustrated with this program!
I got the report to compile with the calendar - put it in the report and was told not a text field
so i need to limit the calendar to between startdate and enddate
then i need to make another variable that will print out the date (not just the work sunday) in the header
been at this for 8 hours so i think i am starting to chase myself in circles :)
>>then i need to make another variable that will print out the date (not just the work sunday) in the header

Calendar.getTime will get you the date (again don't put that literally ;))
I think i just have to chase down which variables to use AFTER I create the new calendar and how to use a where day = 0
then how to put all of it in that expression window....If this was just putting into a little java class it would be different
guess you never stop learning!
Again thank you for sticking this out with me...
I am going to start from the beginning and see if I can hash out some of these variables...when I get to the point that I am blowing up the machine - I will post back the steps
so far I have been trying a plethora of codes and got lost!
Okay, I am back at it
These are the steps that I feel I need to take

1


set start and end date that calendar will use:
$P{startDate}.getDate() - returns an 1 as it is the 1st of november 2010
$P{endDate}.getDate() - returns an 8 as it is the 8th day of november 2010
Is this the recommended format for what I am trying to do?

2


configure Calendar:
new GregorianCalendar() set the calendar that I wish to pull week beginning dates from - report compiled correctly at this point - when placed in the report the return was a lot of code, including shot of report - however I believe it worked correctly!

3


Created Variable for first day of week:
$V{Calender}.getFirstDayOfWeek() - Report compiled correctly and when placed the variable in report it displayed a 1 - as the getfirstdayofweek method returns an int - not sure if this is configured correctly as it returns 11 fields

4


Things I now need to accomplish is converting day of week to datetime or at least displaying the date fetched
setting the parameters to only configure between the startdate and the enddate
Could use some help here.
As you can see I am configuring each variable seperately as it seems the method that must be used when doing calculations inside of iReport. For this particular job I am confined in that I can not create the weekly breakdown inside of my stored procedure


oops pick again!
formatting-windo.JPG
wrong one!

gregoriandates.JPG
>>$P{startDate}.getDate()

Not sure what 'P' is there. You should probably generally be using Calendar
in iReports
$P = param that is used in report - usually what is created by iReport or what is passed from the stored proceudre

$F is a field that is passed from the stored procedure

$V is a variable that is created within iReport
Those fields are probably not very useful for this report - The startDate is actually a dateTime but I can change it to other types of format....Date...so forth
you could use a similiar technique as used to display a calendar month

Also getting the first day of the current week may help you

> Is this the recommended format for what I am trying to do?

No, that is deprecated, use the Calendar class to get the fields needed

> wrong one!

will need to format a Calendar to display it
going about this a different way - how would i convert the weekofyear to a date display
Well you'd have to decide, given a week number, what part of the week you wanted to show. Beginning,end or what?
given a week number I would like to convert sunday to the date as the heading i am going to use.....BTW boy am I learning a LOT about jasper reports!
You'd be getting the week number from where- a Calendar instance?
$V{Calender}.get(Calendar.WEEK_OF_YEAR)
You can do the following
$V{Calender}.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
// Now $V{Calender}.getTime() will give you the beginning date of that week

Open in new window

this returns today's date

I must be making this too hard...surely it cant be this difficult! I give up!
>>this returns today's date

Shouldn't do. It certainly should be some Sunday ;) Sounds like the set operation might have done nothing - check before and after call
what do you currently have?
@cehj I tried emailing you but it was undeliverable!
 new information for this problem!
the following is an example of how a variable can be used - My issue is what to put where - and figuring out what can be compared or cast:

iReports: variable for endDate parameter class = java.util.date
listed under the box: default value expression:
? DateUtils.addDays(new Date(),1)
:   $P{DateRange}.equals("yesterday")
    ? new Date()
    :   $P{DateRange}.equals("tomorrow")
        ? DateUtils.addDays(new Date(),2)
        :   $P{DateRange}.equals("this week")
            ? DateUtils.addDays(
                new Date(),/* the formula on the next line returns the number of says since Sunday */
                7 - (DateFormatUtils.format(new Date(),"E").equals("Sun") ? 0 : DateFormatUtils.format(new Date(),"E").equals("Mon") ? 1 : DateFormatUtils.format(new Date(),"E").equals("Tue") ? 2 : DateFormatUtils.format(new Date(),"E").equals("Wed") ? 3 : DateFormatUtils.format(new Date(),"E").equals("Thu") ? 4 : DateFormatUtils.format(new Date(),"E").equals("Fri") ? 5 : 6)
              )
            :   $P{DateRange}.equals("last week")
                ? DateUtils.addDays(
                    new Date(),/* the formula on the next line returns the number of says since Sunday */
                    -1 * (DateFormatUtils.format(new Date(),"E").equals("Sun") ? 0 : DateFormatUtils.format(new Date(),"E").equals("Mon") ? 1 : DateFormatUtils.format(new Date(),"E").equals("Tue") ? 2 : DateFormatUtils.format(new Date(),"E").equals("Wed") ? 3 : DateFormatUtils.format(new Date(),"E").equals("Thu") ? 4 : DateFormatUtils.format(new Date(),"E").equals("Fri") ? 5 : 6)
                  )
                :   $P{DateRange}.equals("next week")
                    ? DateUtils.addDays(
                        new Date(),/* the formula on the next line returns the number of says since Sunday */
                        14 - (DateFormatUtils.format(new Date(),"E").equals("Sun") ? 0 : DateFormatUtils.format(new Date(),"E").equals("Mon") ? 1 : DateFormatUtils.format(new Date(),"E").equals("Tue") ? 2 : DateFormatUtils.format(new Date(),"E").equals("Wed") ? 3 : DateFormatUtils.format(new Date(),"E").equals("Thu") ? 4 : DateFormatUtils.format(new Date(),"E").equals("Fri") ? 5 : 6)
                      )
                    :   $P{DateRange}.equals("this month")
                        ? DateUtils.truncate(DateUtils.addMonths(new Date(),1),Calendar.MONTH)
                        :   $P{DateRange}.equals("last month")
                            ? DateUtils.truncate(new Date(),Calendar.MONTH)
                            :   $P{DateRange}.equals("next month")
                                ? DateUtils.truncate(DateUtils.addMonths(new Date(),2),Calendar.MONTH)
                                : new Date() /* if all tests fail then we default to today */

listed under the text filed expression paramater class = java.lang.string
"EndDate:\n" +
DateFormatUtils.format(
    $P{EndDate},
    DateFormatUtils.ISO_DATE_FORMAT.getPattern()
)

these are the windows in which i can place some code
CAN NOT use: if else for or while
can create statements such as
($F{quantity}== null ? "No Data" : String.valueOf($F{quantity})

For this report:
I have a startdate and enddate - passed as either Date or Timestamp
I need to find ALL sundays between these time dates and print them out.

This would seem to be a rather simple thing to do - so far it is not and after posting to the ireport support forum - NO help!

I can create variables that manipulate the fields and parameters.
so with these constraints how would you go about getting to the list of printed Sundays with the Dates for those sundays printed out
IE ("Week Of" + (the date printed out for each sunday between startdate and enddate)
I am SURE that this has already been answered somewhere in these 36 message but can someone PLEASE HOLD MY HAND on this one.
Thanks

additional input - the code that uses the $P{DateRange} param will not work for me because I would need to 1. change the st_proc and 2. prompt for a time frame such as 'week' which is not going to work for this client

>>I need to find ALL sundays between these time dates and print them out.

Well you'll need to loop in the script - can you do that?
not sure, but I just found another little work around that someone did....
to find sunday
((new java.util.Calendar()).setTime($F{mydate})).get(Calendar.DAY_OF_WEEK)
==java.util.Calendar.SUNDAY?"sunday":"not sunday"

and then this:
int y = Y - (14 - M) / 12;
int x = y + y/4 - y/100 + y/400;
int m = M + 12 * ((14 - M) / 12) - 2;
int d = (D + x + (31*m)/12) % 7;

I believe I would have to create an individual variable or for each int?

looks like there has been some success with this code format for loops
$F{X}.toString().equals("")?  "No data found" : $F{X}

((new java.util.Calendar()).setTime($F{mydate})).get(Calendar.DAY_OF_WEEK)
==java.util.Calendar.SUNDAY?"sunday":"not sunday"
gave me these errors

cannot invoke get(int) on primitive type void
cannot instantiate the type calendar
more info:
<condition> ? <if true> : <if false>
You can cascade them like this:
<condition1> ? <if condition1> : <condition2> ? <if condition2> : <last else>
Of course you could have more than one layer of nesting, too. Your <if true> and <if false> items must be the class type that yopu want to display. For example:
$F{some_number} >= 5 ? "It's bigger" : "It's smaller"
In this case the class type would be String. Make sense?

afater going through the iReport using search work loop this is the only additional information I found. Most of these questions go unanswered
Can you just establish you can do a simple loop and show me the simplest code for that?

@cehj This is what I have found in the "developer guide"  

In spite of the possible complexity of an expression, usually it is a simple operation that returns a value. It is not a snippet of
code, or a set of many instructions, and you cannot use complex constructs or flow control keywords, such as switches, loops,
for and while cycles, if and else.
Be that as it may, there is a simple if-else expression construct that is very useful in many situations. An expression is just an
arbitrary operation (however complicated) that returns a value. You can use all the mathematical operators or call object
methods, but at any stage the expression must represent a value. In Java, all these operators can be applied only to primitive
values, except for the sum operator (+). The sum operator can be applied to a String expression with the special meaning of
“concatenate”. So, for example:

A way to create an if-else-like expression is by using the special question mark operator. Here is a sample:
(($F{name}.length() > 50) ? $F{name}.substring(0,50) : $F{name})
The syntax is (<condition>) ? <value on true> : <value on false>. It is extremely useful, and the good news is
that it can be recursive, meaning that the value on true and false can be represented by another expression which can be a
new condition:
(($F{name}.length() > 50) ?
(($F{name}.startsWidth(“A”)) ? “AAAA” : “BBB”)
:
$F{name})
This expression returns the String “AAAA” when the value of the field name is longer than 50 characters and starts with A,
returns BBB if it is longer than 50 characters but does not start with A, and, finally, returns the original field value if neither of
these conditions is true.
Despite the possible complexity of an expression (having multiple if-else instructions and so on), it can be insufficient to
define a needed value. For example, if you want to print a number in Roman numerals or give back the name of the weekday
of a date, it is possible to transfer the elaborations to an external Java class method, which must be declared as static, as shown
in the following:

THOUGHTS?
I actually wound up changing the sql - even though that is the one thing i did not want to do!
The java code you gave works as well just not for jasper!
:)