Java Convert String to Date and Compare
Here is a code to convert Java String to date and compare with date field in MySQL table.
This conversion is done to make comparison easier with the date field in MySQL table, so i have not used Simple Date Format function. Using Simple date format you can change the format of date.
This code is tested in Netbeans.

MySQL Table:

create table datecheck
(
sdate DATE primary key not null
)

Note: Insert sample date using mysql query, I have inserted a date: “insert into datecheck values(‘2015-08-20’)

convert.java

public class convert {
    public static void main(String args[])
    {
        String tdate="08/19/2015";
        Date d=null;
        Date d1=null;
        try
        {
                Class.forName("com.mysql.jdbc.Driver");  
                Connection con=DriverManager.getConnection("URL", "Username", "password");
                Statement stmt=con.createStatement();
                ResultSet rs1=stmt.executeQuery("select STR_TO_DATE('"+tdate+"','%m/%d/%Y') as tr");
                while(rs1.next())
                 {
                     d=rs1.getDate("tr");
                 }
                System.out.println(d);
                ResultSet rs=stmt.executeQuery("select * from datecheck");
                 while(rs.next())
                 {
                     d1=rs.getDate("sdate");
                 }
                        if(d1.compareTo(d)>0)
                        {
                            System.out.println("d1 date is greater than d date");
                        }
                        else
                        {
                            System.out.println("d1 date is Less than d date");
                        }
        }
        catch(Exception e)
        {
            e.printStacktrace();
        }
    } 
}

 

Java String to Date conversion and compare with date in mysql, java string to date, string to date conversion

 

By Sri

One thought on “Java Convert String to Date and Compare”

Leave a Reply

Your email address will not be published. Required fields are marked *