Solved

date string with actual date comparing

Posted on 2004-08-19
18
222 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
[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
  • 9
  • 4
  • 3
  • +1
18 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 11843946
because they are different classes...

compare the getTime(), not the objects

0
 
LVL 35

Expert Comment

by:TimYates
ID: 11843957
   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
ID: 11843998
Hi vaibhavmishra,

they are unequal because you create them at different time.

Regards
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 35

Expert Comment

by:girionis
ID: 11844001

> 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
ID: 11844012
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
ID: 11844022
> 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
ID: 11844083
> 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
ID: 11844091

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
ID: 11844232
so....what girionis said?
0
 
LVL 35

Expert Comment

by:girionis
ID: 11844311
> 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
ID: 11849469
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
ID: 11849875
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
ID: 11851425

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
ID: 11851541
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
ID: 11851735
indeed we are, many appologies (I really need a holliday!!! starting to see things here ;-( )
0
 

Author Comment

by:vaibhavmishra062201
ID: 11853384
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
ID: 11853540
> 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
ID: 11880581
:)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How do I remove an object from a 3 53
CSV file parsing thru Java 13 40
eclipse console opening separately 2 38
running on tomcat not jboss eap 7.0 3 32
In this post we will learn different types of Android Layout and some basics of an Android App.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

733 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