Solved

how to use .getdayofweek

Posted on 2011-03-09
46
904 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
  • 24
  • 14
  • 6
  • +1
46 Comments
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
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
Comment Utility
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
Comment Utility
and that will give me every sunday between date ranges - now to just get it to work inside iReports!

0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
Comment Utility
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
Comment Utility
@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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
ooops here is the expression box which allows me to put code into iReports

formatting-windo.JPG
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
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
Comment Utility
Sorry
new java.util.GregorianCalendar().setTime($F{Call Started}).xxxxxx

Open in new window

0
 

Author Comment

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

Author Comment

by:tagomtech
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
>>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
Comment Utility
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
Comment Utility
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
Comment Utility
oops pick again!
formatting-windo.JPG
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:tagomtech
Comment Utility
wrong one!

gregoriandates.JPG
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>$P{startDate}.getDate()

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

Author Comment

by:tagomtech
Comment Utility
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
Comment Utility
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
Comment Utility
going about this a different way - how would i convert the weekofyear to a date display
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
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
Comment Utility
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
Comment Utility
You'd be getting the week number from where- a Calendar instance?
0
 

Author Comment

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

Expert Comment

by:CEHJ
Comment Utility
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
Comment Utility
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
Comment Utility
>>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
Comment Utility
what do you currently have?
0
 

Author Comment

by:tagomtech
Comment Utility
@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
Comment Utility
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
Comment Utility
>>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
Comment Utility
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
Comment Utility
((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
Comment Utility
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
Comment Utility
Can you just establish you can do a simple loop and show me the simplest code for that?
0
 

Author Comment

by:tagomtech
Comment Utility

@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
Comment Utility
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
Comment Utility
:)
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
wordcount challenge 11 73
wordmultiple challenge 12 89
Running Jira on Raspberry PI 2? 3 117
mockito example issue 8 29
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now