Solved

how to use .getdayofweek

Posted on 2011-03-09
46
962 Views
Last Modified: 2012-05-11
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
0
Comment
Question by:tagomtech
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 24
  • 14
  • 6
  • +1
46 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 35084334
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...
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35084356
You can use

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

Author Comment

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

0
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

 
LVL 47

Expert Comment

by:for_yan
ID: 35084377
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
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35084508
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
0
 

Author Comment

by:tagomtech
ID: 35084537
@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.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35084597
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);


}


0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 35084668
Try something like the following
import java.text.*;

import java.util.*;


public class Weeks {
    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();
        int start = -1;

        while (start != Calendar.SUNDAY) {
            c.add(Calendar.DATE, 1);
            start = c.get(Calendar.DAY_OF_WEEK);
        }

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 6; j++) {
                System.out.printf("%-12tA%<td\n", c.getTime());
                c.add(Calendar.DATE, 1);
            }

            System.out.println();
        }
    }
}

Open in new window

0
 

Author Comment

by:tagomtech
ID: 35085617
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.


0
 
LVL 47

Expert Comment

by:for_yan
ID: 35085700
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()  - ?
0
 

Author Comment

by:tagomtech
ID: 35085832
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}


0
 

Author Comment

by:tagomtech
ID: 35085853
ooops here is the expression box which allows me to put code into iReports

formatting-windo.JPG
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35085892
Try the following (as you need a Calendar) then examine the fields
new Calendar().setTime($F{Call Started}).xxxxxx

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35085908
Sorry
new java.util.GregorianCalendar().setTime($F{Call Started}).xxxxxx

Open in new window

0
 

Author Comment

by:tagomtech
ID: 35085979
@cehj errors
cannon instantiate the type calendar and xxxxxxxx cannon be resolved or is not a field
0
 

Author Comment

by:tagomtech
ID: 35086028
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

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35086391
I didn't mean literally to type a row of xxx ;) That's intended for the field or method you want
0
 

Author Comment

by:tagomtech
ID: 35086451
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 :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35086518
>>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 ;))
0
 

Author Comment

by:tagomtech
ID: 35086586
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!
0
 

Author Comment

by:tagomtech
ID: 35087816
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


0
 

Author Comment

by:tagomtech
ID: 35087902
oops pick again!
formatting-windo.JPG
0
 

Author Comment

by:tagomtech
ID: 35087945
wrong one!

gregoriandates.JPG
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35088338
>>$P{startDate}.getDate()

Not sure what 'P' is there. You should probably generally be using Calendar
0
 

Author Comment

by:tagomtech
ID: 35088383
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
0
 
LVL 92

Expert Comment

by:objects
ID: 35089490
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
0
 

Author Comment

by:tagomtech
ID: 35097012
going about this a different way - how would i convert the weekofyear to a date display
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35097096
Well you'd have to decide, given a week number, what part of the week you wanted to show. Beginning,end or what?
0
 

Author Comment

by:tagomtech
ID: 35097121
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!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35097160
You'd be getting the week number from where- a Calendar instance?
0
 

Author Comment

by:tagomtech
ID: 35097222
$V{Calender}.get(Calendar.WEEK_OF_YEAR)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35097534
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

0
 

Author Comment

by:tagomtech
ID: 35097923
this returns today's date

I must be making this too hard...surely it cant be this difficult! I give up!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35097974
>>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
0
 
LVL 92

Expert Comment

by:objects
ID: 35099613
what do you currently have?
0
 

Author Comment

by:tagomtech
ID: 35109540
@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

0
 

Author Comment

by:tagomtech
ID: 35109581
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

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35109946
>>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?
0
 

Author Comment

by:tagomtech
ID: 35110017
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}

0
 

Author Comment

by:tagomtech
ID: 35110073
((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
0
 

Author Comment

by:tagomtech
ID: 35110198
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
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35110357
Can you just establish you can do a simple loop and show me the simplest code for that?
0
 

Author Comment

by:tagomtech
ID: 35111958

@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?
0
 

Author Closing Comment

by:tagomtech
ID: 35199959
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!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35200022
:)
0

Featured Post

What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question