Solved

date string with actual date comparing

Posted on 2004-08-19
18
193 Views
Last Modified: 2010-03-31
Hi,

I am using j2sdk1.4.2
I am getting a date as string in dd/MM/yy format
I am having another date as java.sql.Date

I want to check whether both are equal or not.
Please  check the following code and tell me why dates are not equal during first comparison ?
If you can suggest a better fool proof way to do it, it will be appreciated.
=======================
import java.text.*;
import java.util.*;

public class DateTest
{
      public static void main(String[] args)  throws Exception
      {
            java.sql.Date dateSQL=new java.sql.Date(System.currentTimeMillis());

            //////////////////////////////////////////////////////////
            //replace with today date string in dd/MM/yy format
            String todayDate="19/08/04";

            SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yy");
            java.util.Date dateUtil=sdf.parse(todayDate);
            long l=dateUtil.getTime();
            java.sql.Date dateSQL2=new java.sql.Date(l);

            System.out.println(dateSQL);
            System.out.println(dateSQL2);

            if(dateSQL.equals(dateSQL2))
                  System.out.println("equal");
            else
                  System.out.println("unequal");

            StringTokenizer stk1=new StringTokenizer(dateSQL.toString(),"-");
            int year1=Integer.parseInt(stk1.nextToken());
            int month1=Integer.parseInt(stk1.nextToken());
            int day1=Integer.parseInt(stk1.nextToken());

            StringTokenizer stk2=new StringTokenizer(dateSQL2.toString(),"-");
            int year2=Integer.parseInt(stk2.nextToken());
            int month2=Integer.parseInt(stk2.nextToken());
            int day2=Integer.parseInt(stk2.nextToken());

            if(year1==year2 && month1==month2 && day1==day2)
                  System.out.println("equal");
            else
                  System.out.println("unequal");
      }
}
===========================
vaibhav
0
Comment
Question by:vaibhavmishra062201
  • 9
  • 4
  • 3
  • +1
18 Comments
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
because they are different classes...

compare the getTime(), not the objects

0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
   if(dateSQL.equals(dateSQL2))

should be

    if( dateSQL.getTime() == dateSQL2.getTime() )

one of them is a java.util.Date, the other is a java.sql.Date
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Hi vaibhavmishra,

they are unequal because you create them at different time.

Regards
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility

> java.sql.Date dateSQL=new java.sql.Date(System.currentTimeMillis());
>
>           //////////////////////////////////////////////////////////
>           //replace with today date string in dd/MM/yy format
>           String todayDate="19/08/04";
>
>           SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yy");
>           java.util.Date dateUtil=sdf.parse(todayDate);
>           long l=dateUtil.getTime();
>           java.sql.Date dateSQL2=new java.sql.Date(l);

You create the second date a few milliseconds later.
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Tim it shouldn't matter since sql Date inherits from util Date. The equals method compares their time anyway.
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
> You create the second date a few milliseconds later.

Actually no, you create the second date on the midnight on 19/08/2004 while you create the first date right now.
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
> You create the second date a few milliseconds later.

Ooooh yeah...missed that :-)

>  Tim it shouldn't matter since sql Date inherits from util Date.

I forgot that :-(  *blush*

Wish I hadn't posted here now ;-) hehehehe

/me runs off and hides

;-)
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility

Hi,

Its not to do with when they are created, as the second is created with the milliseconds from the first...

The latter (i.e. java.sql.Date) rounds off some time information....

Check the hour/minute/second values on the data created with the SimpleDateFormat, and then compare this with that of the java.sql.Date
(simply do a System.out.println() on both Date objects!)

quoting from JavaDoc for java.sql.Date:

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular  time zone with which the instance is associated.

Cheers,
C
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
so....what girionis said?
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 35

Expert Comment

by:girionis
Comment Utility
> Its not to do with when they are created, as the second is created with
> the milliseconds from the first...

Actually this is not true as the second is created from todays date which defaults to 19/08/2004 00:00:00 since it is not given the times.

Tim I always do that (forgeting methods and reading questions too fast) hehe :)
0
 

Author Comment

by:vaibhavmishra062201
Comment Utility
hi

thanks for ur comments but i am confused
uptil now i only knew that java.sql.Date contains day/montht/year part and no hour/minutes ... parts
as it also displays only dd/MMyy parts while doing anything with it

if it contains time part also then definately they must be unequal
are you sure of this ?

if yes, can you suggest any way i can compare the date string in dd/MM/yy to a java.sql.Date
other than the way i compared using StringTokenizer

vaibhav
0
 
LVL 35

Accepted Solution

by:
girionis earned 125 total points
Comment Utility
It contains time, I am pretty sure about this. If you create a date by 20/08/2004 it will default to the first second after 23:59:59 of 19/08/2004, so it will be 00:00:00 20/08/2004. The System.currentTimeMillis() will get you all the milliseconds up to the time you call it. So if you call it at 00:00:10 20/08/2004 it will get you 10000 milliseconds more than the date 20/08/2004.

Now if you want to compare only the dates (day, month, year) without the time then the simplest thing you can do (without affecting your code that much) is to count the milliseconds and subtract the difference. Something like:

private static final long millisecondsInADay = 1000 * 60 * 60 * 24;

if (dateSQL.getTime() - dateSQL2.getTime() > millisecondsInADay)
              {
                    System.out.println("unequal");
              }
              else
              {
                    System.out.println("equal");
              }

Otherwise you better create two calendar instances of the current date and the current date and time and compare their fields, DAY_OF_YEAR, MONTH, YEAR. If they are the same then the dates are equal otherwise unequal.
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility

girionis, the second object is created with the milliseconds of the first date object, not created with the default constructor, so, it is not different because it is created later!

>           long l=dateUtil.getTime();
>           java.sql.Date dateSQL2=new java.sql.Date(l);

this is a longer version of "java.sql.Date dateSQL2 = new java.sqlDate( dateUtil.getTime() )", albeit "dateUtil" is a strange name for an instance of Date...
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
I think we have confused the objects. As first object I mean dateSQL, as second object I mean dateSQL2.
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
indeed we are, many appologies (I really need a holliday!!! starting to see things here ;-( )
0
 

Author Comment

by:vaibhavmishra062201
Comment Utility
thanx girinois, you should also check 2nd condition -
===============================
//unequal
if(dateSQL.getTime() - dateSQL2.getTime() > millisecondsInADay
    && dateSQL.getTime() - dateSQL2.getTime() < 0)
===============================

btw i have opted for a different way -
========================
if(dateSQL.getString().equals(dateSQL2.getString()))
    System.out.println("equal");
else
    System.out.println("unequal");
========================
ne comments about that ?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
> if(dateSQL.getString().equals(dateSQL2.getString()))

It's the same thing you can use either approach. But as long as you are happy then it's fine. It does not really matter what approach you will use to solve a problem. I always advocate the "make it work first and optimize later" dogma.
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
:)
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

772 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

10 Experts available now in Live!

Get 1:1 Help Now