Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing MySQL and Java Time

I have a datetime field in MySQL which I access through calling result.getString('date'), now I would like to check weather the current date and time in Java has exceeded the MySQL time or is before the MySQL time to check weather a result is activated or not.

Datetime from MySQL has the form: 2011-12-30 17:10:00, how can I compare this string to the Java time?

like image 468
Dominik Avatar asked Jun 01 '11 15:06

Dominik


2 Answers

In Java, you can construct a Date from a string, using a SimpleDateFormat:

String text = "2011-12-30 17:10:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(text);
Date now = new Date();

if (date.after(now))
{
    // do stuff
}

You can instead perform similar operations in the database, using basic arithmetic and (I think) equality operators: +, -, >, <, etc., as well as MySQL's date and time functions.

...though I'm curious to know why you are using getString() instead of ResultSet#getTimestamp().


One other word of advice: consider using Joda Time instead of java.util.Date and java.util.Calendar. See Should I use Java date and time classes or go with a 3rd party library like Joda Time?

like image 138
Matt Ball Avatar answered Sep 27 '22 20:09

Matt Ball


Prior to JDK 8

You can use ResultSet.getDate('date') to retreive a Date object. Then use the method Date.before() or Date.after() to check.

JDK 8 or later

Refer to Basil Bourque's answer below.

like image 40
Genzer Avatar answered Sep 27 '22 20:09

Genzer