Compare date with implements Comparator
I have a DefaultListModel (mode) staffed with EMPL (id, name, startingDate). I would like to sort the defaultListModel accourding to the dob. for this I do the following:
Object[] contents = model.toArray();
Arrays.sort(contents, new ComparatorDate());
model.copyInto(contents);the comparator: ComparatorDate
public class ComparatorDate implements Comparator
public int compare(Object o1, Object o2)
Empl a = (Empl ) o1;
Empl b = (Empl ) o2;
Date d1 = a.getStartDate();
Date d2 = b.getStartDate();
return (d1.getDate()-d2.getDate());
}when debugging I realize the dates are diff but the d1.getDate()=1 and d2.getDate()=1 ??? how come? the result are not what expected.
any idea?
getDate() tells you the day of the month. Both your dates are apparently on the first of some month. Since Date implements Comparable, why not just do return d1.compareTo(d2)
Similar Messages
-
How to compare user entered date with current date
Hi all
my requirement is, user allowed select one date, in code i have compare this date with current day date. it should be 15days gap other wise display error message.
I am worried about how to get current date in code. Is there any code to get current date. please reply me with code or mail me at [email protected]
Thanx
keerthiKeerthi,
Use the method <b>getDifference()</b> of the DateHelper.java available here.<a href="http://www.koders.com/java/fid14A61FEB1B45A64E42E1DCAD7070B46AE46340BA.aspx">DateHelper</a>
1. Create a new folder, say Util under your src folder. (com.xyz.util)
2. Put this DateHelper.java file in that folder,(com.xyz.util) .
3. Now, write an import statement for this java class in the required view.
4. Use the getDifference() method of this class to the difference in days between two days.
Or
Simply use this code.
// Get msec from each, and subtract.
long diff = currDate.getTime() - selectedDate.getTime();
int noOfDays = diff / (1000 * 60 * 60 * 24);
where currDate is today's Date and selectedDate is the Date selected by the User.
Bala -
How to compare a Date data with Current Year and Period Member on FIX
Hi experts,
I have a Project dim that each member is a Project (P01, P02...)
and Account dim that stores information of the each Project (Name, Start date, Finished Date...)
Finished Date member is in Date data type
So how can write a IF condition below in order to compare Project Finished Date with Current Year and Period members on FIX
FIX (@Descendants(Projects), Descendants(All Year), Descendants("Year Total")...)
IF (@CURRMBR(Period)->@CURRMBR(Year) < Project->FinishedDate)
Do something...
Else
Do something
Please help me on this. Sorry for my bad grammar. Please ask if there is anything unclear
Many thanks,
Huy Van.
Edited by: Huy Van on Jan 29, 2013 1:14 AM
Edited by: Huy Van on Jan 29, 2013 2:24 AM
Edited by: Huy Van on Jan 29, 2013 2:25 AM
Edited by: Huy Van on Jan 29, 2013 6:04 PMHere is what I have done. Post for whom may concern later
VAR FM; /* Finished Month of Project*/
VAR FY; /* Finished Year of Project */
VAR CM; /* Capture Current Month on FIX statments */
VAR CY; /* Capture Current Year on FIX statments*/
FIX ( @RELATIVE( "Year", 0), @RELATIVE( "Period", 0), @IDescendants( "Base Projects")....)
FY = @ROUND( "TGHT"->"NA Contract"->"FY06"->"NA Period" / 10000, 0);
FM = @MOD( @ROUND( "TGHT"->"NA Contract"->"FY06"->"NA Period" / 100, 0), 100);
/* For FY13 return 13... */
CY = @JgetDoubleFromString( @CONCATENATE( "20", @SUBSTRING( @NAME( @CURRMBRRANGE( Year, Lev, 0, 0, 0)), 2)));
/* Set CM value based on currrent Period On FIX statement */
IF ( @ISMBR( "Jan"))
CM = 1;
ELSEIF ( @ISMBR( "Feb"))
CM = 2;
ELSEIF ( @ISMBR( "Dec"))
CM = 12;
ENDIF
IF ( CY < FY OR ( CY == FY AND CM < FM))
Do something...
ELSE
Do something...
ENDIF
ENDFIX
Edited by: Huy Van on Feb 19, 2013 11:10 PM
Edited by: Huy Van on Feb 20, 2013 7:46 PM -
How to compare current date with past date
Sample code for comparing current date with past date
i dont want to Calender.set method to compare it.
How can i do it?PLEASE stay with ONE thread:
http://forum.java.sun.com/thread.jspa?threadID=5143991&tstart=0 -
hi
i am having date from and date to feilds in my overtime element.i want to do the validation on these dates the the dates do not overlap or duplicated.the input value date from and date to are stored in database as varchar2 in the format yyyy/mm/dd 00:00:00. Now if i am trying to compare entered date with these dates i am getting literal does not match format string or date picture ends before....Can any body tell me what to do.
Regardsuser10502390 wrote:
hi
i am having date from and date to feilds in my overtime element.i want to do the validation on these dates the the dates do not overlap or duplicated.the input value date from and date to are stored in database as varchar2 in the format yyyy/mm/dd 00:00:00. Now if i am trying to compare entered date with these dates i am getting literal does not match format string or date picture ends before....Can any body tell me what to do.
RegardsPoint a) VERY BAD IDEA storing dates as VARCHAR2 on the database. It will only lead to corrupt data in the future.
Point b) When comparing dates, you should compare them as DATE datatype as the database knows how to do comparisons against DATES. If you try and compare them as VARCHAR2 then you will most likely end up with incorrect comparisons.
If you must have varchar2 storing of your dates/times (there's absolutely no reason to though)... you want...
TO_DATE(:entered_date,'YYYY/MM/DD HH24:MI:SS') BETWEEN TO_DATE(DATEFROM,'YYYY/MM/DD HH24:MI:SS') AND TO_DATE(DATETO,'YYYY/MM/DD HH24:MI:SS')
e.g.
TO_DATE('20080815 13:23:33','YYYY/MM/DD HH24:MI:SS') BETWEEN TO_DATE(DATEFROM,'YYYY/MM/DD HH24:MI:SS') AND TO_DATE(DATETO,'YYYY/MM/DD HH24:MI:SS') -
Compare current time and date with last modified?
Compare current time and date with last modified?
What is the ideal way to compared the last modified from the File class with the current date and time? last modifed value from File class is a long.798642 wrote:
So what do I do to compare whether the current date and time and later than the lastModified ?
if(file.lastModified() < System.currentTimeMillis()) {
Like that?That tests whether the last modified time is before "now"--that is if the file was not modified in the future, so, yes. -
UDF to compare the dates with the input date
Hi,
Help me in writing an UDF to compare the input date with start date and end date.
I had written following UDF, but it is not working. we are on XI 3.0
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date sd = df.parse(StartDate);
Date id = df.parse(InputDate);
Date ed = df.parse(EndDate);
if ((sd.before(id) || (sd.equals(id))) && (ed.after(id)) || (ed.equals(id))) {
return true;
else{
return false;
} catch (Exception e){
e.printStackTrace();
Thanks
SrinivasHello Srinivas,
did you import this two classes in your UDF ? java.text.* and java.util.*
In case you did but the program is still not working I just wrote a code without imports. See if this might help. I have tested this with all type of data please test again from your end. I have assumed that if three dates are equal the function return true. I am not sure whether you wanted to exclude the boundary dates. In case you want to exclude those dates just replace '<=' with '<' symbol. The code could have been smarter but in short time I thought this might help.
public class DateRange {
static boolean compareDate(String startDate,String inputDate,String endDate)
int j,k,l;
String s[],i[],e[];
s=startDate.split("-", 3);
i=inputDate.split("-", 3);
e=endDate.split("-", 3);
j=s[0].compareTo(i[0]);
k=i[0].compareTo(e[0]);
l=s[0].compareTo(e[0]);
if(l>0|| j>0 || k>0)
return false;
if(j<=0 && k<0)
return true;
j=s[1].compareTo(i[1]);
k=i[1].compareTo(e[1]);
l=s[1].compareTo(e[1]);
if(l>0|| j>0 || k>0)
return false;
if(j<=0 && k<0)
return true;
j=s[2].compareTo(i[2]);
k=i[2].compareTo(e[2]);
l=s[2].compareTo(e[2]);
if(l>0|| j>0 || k>0)
return false;
if(j<=0 && k<=0)
return true;
return false;
public static void main(String[] args) {
String startDate="1992-04-03";
String inputDate="1992-02-03";
String endDate="1992-02-03";
System.out.println(compareDate(startDate,inputDate,endDate));
Plese let me know if this works.
regards
Anupam -
Hi,
I have a Date which is stored in the Database with the timezone like GMT, I have a java.util.Date which is selected in my UI from a Customized Calendar, I am converting this Date with timezone and want to compare this date with the date with timezone stored in the DB? How to accomplish this, please shed some light into this?
Thanks.797836 wrote:
I have a Date which is stored in the Database with the timezone like GMT, I have a java.util.Date which is selected in my UI from a Customized Calendar, I am converting this Date with timezone and want to compare this date with the date with timezone stored in the DB?As Parul said, Date does not involve a timezone. I think you need to clarify what you mean by "I am converting this Date with timezone", because it doesn't make much sense to me.
BTW: If the date in your database is a standard SQL Date, then it will be converted to a java.sql.Date when you read it into Java with JDBC. And java.sql.Date is directly comparable with java.util.Date (in fact, it's a subclass).
Winston -
Compare finish date with target date
Would like to keep track of late Projects by comparing the finish date with the target date but are unable to do so. The idea is just to filter and count the summary tasks which have a later Finish date than the target date and present that as a the number
of late Projects. However it does not work, when trying to setup the filter Project tells that the target value can not be used for comparasion against the finish date.
Does anyone have a workaround or maybe a better solution to keep track of late Projects. Please note that we are talking about Projects that risk to be late compared to a date promised to a customer. When we plan we always add some extra time at the
end to have some extra when the Project is delayed at a certain department, however we want to keep track of how many late Projects we have and how late they are. Are not after seeing the status for each departments, only how we are doing in relation to what
we have promised our customers.
Kind regards //AndersAnders,
Trevor and Dale have tried to steer you towards the normal tracking fields and methods already available in Project, but let me take a more direct approach to your exact question. First of all, you didn't tell us what field you are using as the "target date".
I'll assume it is the Date1 field manually entered for each summary line.
You could probably produce something close to the report you want with custom field formulas, filters and some manual counting but let me offer a more automated approach. The following macro will examine each summary task in your project and determine if
the finish date is before or on the target date (Date1), or if it is after the target date. If it is after the target date, that will count as one late project/order and add it to a running count of late orders. The difference in days will also be tracked
and added to a running total of delay. At the end, a message will appear in the exact format you describe.
Sub LateReport()
Dim t As Task
Dim LateCount As Integer
Dim LateDays As Integer
Dim TotDelay As Integer
For Each t In ActiveProject.Tasks
If Not t Is Nothing Then
If t.Summary = True Then
If DateValue(t.Finish) > DateValue(t.Date1) Then
LateCount = LateCount + 1
LateDays = DateValue(t.Finish) - DateValue(t.Date1)
TotDelay = TotDelay + LateDays
End If
End If
End If
Next t
MsgBox "Number of late orders: " & LateCount & " (" & TotDelay & " days of total delay)"
End Sub
Note, in my view, and I'm sure in Trevor and Dale's also, the Finish field of the summary line does not indicate completion, it simply indicates the scheduled finish date of the last task in the subtasks under that summary. I think you should use the Actual
Finish date as the comparison value since it indicates when the project/order is complete. If you do decide, actual finish is a better choice, then substitute t.ActualFinish for t.Finish in the above macro.
My input.
John -
Comparing AWR data with baselines.
Hello,
I am studying AWR, which will be used in our project for performance analysis.
My requirement is to create a baseline of load between 2 snapshots during normal system load. We perform load/stress testing before final deployment. We are planning to take snapshots before and after load/stress tests. I want to compare the performance of instance during load/stress test with that of baseline performance.
Oracle provides package DBMS_WORKLOAD_REPOSITORY for different functions of AWR. It provides function CREATE_BASELINE function for creating baseline. But in report generation function AWR_REPORT_HTML or AWR_REPORT_TXT no parameter is specified for comparing it with the baseline.
Is it possible to compare AWR data with baseline, during report generation? Or currently Oracle supports only baseline creation and dropping that baseline. It can not be used for performance comparison.
Thanks,
ShaileshHi,
Take a look on the note: 543188
With rgds,
Anil Kumar Sharma .P
Kindly Assign the points to the helpful answers.
Message was edited by: Anil Kumar Sharma -
Performance question when compare date with date or char with char
Hello from Germany (Frankfurt) !
I am working on Oracle 9.2.0.8.0
and have to solve following problem:
Comparison of a date and char fields.
Now two ways to do it.
Either I compare char with char and convert date to char,
or I compare date with date and convert char to date.
Now the performace question. Which operation takes more effort for the database?
So why not to try and to see the results?
First create table:
CREATE TABLE TEST (
char_date VARCHAR2(8),
real_date DATE
NOLOGGING;
Then insert 1.000.000 rows
BEGIN
for x in 1..1000000
loop
insert into test (char_date, real_date) VALUES('19990101', TO_DATE('2006.01.01', 'YYYY.MM.DD'));
end loop;
COMMIT;
END;
Collect statistics
EXEC dbms_stats.gather_table_stats('TESTER', 'TEST');
Now run some selects for date to char conversion:
Elapsed: 00:00:00.00
SQL> select * from test t where TO_DATE(char_date, 'YYYYMMDD') > real_date;
no rows selected
Elapsed: 00:00:03.02
SQL> select * from test t where TO_DATE(char_date, 'YYYYMMDD') > real_date;
no rows selected
And some selects for char to date conversion:
Elapsed: 00:00:03.02
SQL> select * from test t where char_date > TO_CHAR(real_date, 'YYYYMMDD');
no rows selected
Elapsed: 00:00:02.05
SQL> select * from test t where char_date > TO_CHAR(real_date, 'YYYYMMDD');
no rows selected
Elapsed: 00:00:02.05
SQL>
As you see when I compare char with char and convert date to char it seems to be faster (almost 1 second)
Is the test correct?
I still not sure, what gets better performance...
Any idea?
Thanks!Depends on whether you want the right results or not.
Why don't you run the following two queries and see if the difference in results tells you anything?:
with t as (select to_date('01/02/2007', 'dd/mm/yyyy') date_col from dual
union all
select to_date('02/02/2007', 'dd/mm/yyyy') from dual
union all
select to_date('03/02/2007', 'dd/mm/yyyy') from dual
union all
select to_date('03/03/2006', 'dd/mm/yyyy') from dual)
select *
from t
where date_col < to_date('04/03/2006', 'dd/mm/yyyy');
with t as (select to_date('01/02/2007', 'dd/mm/yyyy') date_col from dual
union all
select to_date('02/02/2007', 'dd/mm/yyyy') from dual
union all
select to_date('03/02/2007', 'dd/mm/yyyy') from dual
union all
select to_date('03/03/2006', 'dd/mm/yyyy') from dual)
select *
from t
where to_char(date_col) < '04/03/2006'; -
How to compare Sale data with Previous data
Hi Guys,
Any one tell me how we will compare Sales data with Last year Sale data. Is there any T.Code or any kind of Report in the SAP. If available please suggest the same.
Thanks & regards,
Naveen BhatiaHi Naveen,
Did yo ucheck t-code SD01
Regards
Rohit. -
"You can't compare a date with a number" in a formula that worked in Excel
I opened in Numbers an invoice file which was created in Excel. Formula returns hours worked. It has an "if" condition for the date field. I am assuming that that is the reason I get this "You can’t compare a date with a number because their data types are different." What do I do?
Formula reads =IF(SUM(A11)>0,(D11−C11),"") where A11 is a date and D11- C11 are times, ie 4PM and 5PM
Message was edited by: iamzoranJerrold Green1,
I agree with your words about using Sum with a single cell [have no idea why the "creator" of the file did that]; same for the parentheses enclosing subtraction. Yet cleaning it up as you showed me [=IF(A11>0,D11−C11,"") ] I got the same comment
"You can’t compare a date with a number because their data types are different."
Makes me think that t quinn is on to something with his "think the issue is with the expression ">0". Could it be that >0 is the number referred to and <>"" and ISBLANK are not numbers?!
z
PS: I am so happy that I am able to use Spelling and Grammar Checker with Safari on these posts. I was born and raise in old Yugoslavia and I use the Checker with all my emails etc and its a life saver. hahaha -
How to compare date with null value
Hi
I have a date filed and i assigned that input box with context attribute of type Date.
Here my problem is
when the end user not entered any thing (null ) the i have give some defaul date.
so first in the action method i have to check the date with null
if it is null i have to give default date.
so please let me know how to over come this.
thanks
MukeshHi
You can get your date in your action method like
Date newDate=new Date();
Date myDate= wdThis
.wdGetYourComponentNameController()
.wdGetContext()
.currentYourNodeNameElement()
.getYourDateName();
if ( myDate== null) {
wdContext.currentContextElement().setYourDateName(newDate);
else{...........//continue your other validations or calling other methods}
Regards
Abhijith YS
Message was edited by:
Abhijith YS -
Display dropdown by key data with sorting
Hi,
My requirement is to display dropdown by key data with sorting getting this data from XML in KM.
Tell me different possibilities to sort the data.
Regards,
surya.Hi,
Use DropDownByIndex instead of DropDownByKey
Create a node with a attribute for eg. Colors node with Color attribute and add the values in the elements of the node, Bind attribute to DropDownByIndex UI.
Create a custom comparator class like below
import java.util.Comparator;
import com.sap.tc.webdynpro.progmodel.api.IWDNodeElement;
import com.sap.tc.webdynpro.progmodel.repository.enums.WDComponentLifecycleEnumInfo;
public class CustomComparator implements Comparator {
String attribute;
public CustomComparator(String attrib) {
this.attribute = attrib;
public int compare(Object o1, Object o2) {
try
IWDNodeElement units1 = (IWDNodeElement) o1;
IWDNodeElement units2 = (IWDNodeElement) o2;
return units1.getAttributeAsText(attribute).compareTo(units2.getAttributeAsText(attribute));
catch (Exception e)
e.printStackTrace();
//arbitrary order
return 1;
Once you read values in the Colors node, call the sortElements method of the node as below to sort the elements of the node
wdContext.nodeColors().sortElements(new CustomComparator("Color"));
Regards,
Amol
Maybe you are looking for
-
The Airplay icon does not show on my Mac Pro, regardless that it is clicked on display. How can I do to see the Airplay Icon in order to connect my apple TV with my Mac Pro?
-
How do you know who in contacts can receive text messages on iPad?
I upgraded my iOS to 5 on my original iPad. Now I have messaging. However, I have no idea who in my 300 contacts have signed up. Some apps have a way of searching your contacts or Facebook friends to see if they have access to certain games like Wor
-
Cisco ATA 187 - will unregister from CUCM 10.5
Hello, I've got some problems with my Cisco ATA 187. They keep unregistering from time to time. If you shutdown the Interface on the switch and no shut, it gets registered just straight away. According to cdp the device is pingable all the time, just
-
How to keep iPhone cool in hot sun
I live in Florida. Being retired, I enjoy sitting by the pool or fishing from my boat, listening to my collection of music on my iPhone 4S. Many months of the year are quite hot. How can I keep the iPhone cool in the hot sun so I will not get temp
-
Titles in Premiere render washed out.
I don't usually use Premiere for titles, but current project necessitates I used the titling tool. Because of time constraints I'm hoping this is a quick fix. I notice that my titles render their color perfectly and vibrantly in the title edit panel.