0

I have a DATA/TIME field in my MySQL database and I'm trying to convert it to date and time in Java. The date works fine, but in time is set to null. I have tried util.Date as well but I get the same result. How can I convert a DATE/TIME to java.sql.Date without losing the time?

This is my code

 try{
        statement = connection.createStatement();
        resultSet = statement.executeQuery("SELECT orders.id, orders.date         FROM user, orders " +
                "WHERE user.username='" + user.getUsername() + "' AND user.id = orders.user");
        while(resultSet.next()){
            Order order = new Order();
            order.setId(resultSet.getInt(1));
            order.setUser(user);
            order.setDate(resultSet.getDate(2));
            System.out.print(order.getDate());
            System.out.print( " -> " + order);
            orders.add(order);
    }catch(SQLException ex){
        System.out.println(ex);
    }
1

2 Answers 2

1

try this

java.sql.Date date = new Date(resultSet.getTimestamp(2).getTime());
Sign up to request clarification or add additional context in comments.

1 Comment

And then convert Timestamp to Date?
0

You are not asking this, but you could save the date as a long in mysql and just treat it as a number.

To get the date back just do a new java.util.Date(mysqllong).

1 Comment

Yes i thought of that, but i dont decide the fields of my mysql database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.