Comparing java.util.Date with database time (java.sql.Timestamp) - Coddicted

Comparing java.util.Date with database time (java.sql.Timestamp) 1

And so it happened. I stumbled again and this time I was hit by mere milliseconds.

Yeah!!! One sure would find a few milliseconds really insignificant but it gave me a real pain in the a** for a while. All I did was to compare a “cron expression” time (a java.util.Date object) with the timestamp value obtained from the database (which happens to be a java.sql.Timestamp object as I came to know only after this blunder). The task was to compare which time comes “before” and intuitively I used java.util.Date class’s before(Date) method.

Here is a sample code that I wrote afterwards to understand the root cause:

package com;
import java.sql.Timestamp;
import java.util.Date;
public class DateTimestampDiff
{
/**
* @param args
*/
public static void main(String[] args)
{
Date dt = new Date();
Date utilDate = new Date(dt.getTime());
Timestamp sqlTime = new Timestamp(dt.getTime());

System.out.println(“–Comparison of util Date and util Date –“);
System.out.println(” dt.before(utilDate) : ” + dt.before(utilDate));
System.out.println(” dt.after(utilDate) : ” + dt.after(utilDate));
System.out.println(” dt.equals(utilDate) : ” + dt.equals(utilDate));

System.out.println(“–Comparison of util Date and SQL time–“);
System.out.println(” dt.before(sqlTime) : ” + dt.before(sqlTime));
System.out.println(” dt.after(sqlTime) : ” + dt.after(sqlTime));
System.out.println(” dt.equals(sqlTime) : ” + dt.equals(sqlTime));
}
}


Back To Top
Rate this post

One comment on “Comparing java.util.Date with database time (java.sql.Timestamp)

  1. Reply gta online money glitch Jan 3,2014 6:26 pm

    Your way of explaining everything in this piece of writing is genuinely nice, every one can easily know it, Thanks
    a lot.

Leave a Reply