Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a string into a java.sql.date

Hi i am trying to parse a string into a java.sql.date

Here is what i am doing

private static SimpleDateFormat sdfout = new SimpleDateFormat("yyyy.MM.dd.HH.mm");
          try{
            String date = "2010.09.30.13.18";
        task.setDueDate(new java.sql.Date(sdfout.parse(date).getTime()));
    }

The problem is that i only get the date back. Not the time.

Am i doing this correctly

like image 889
Matt Avatar asked Sep 23 '10 14:09

Matt


People also ask

Can we convert string to date in java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

How do you parse a string to a date?

Date.parse() The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

How do you parse a date object in java?

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly): SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

What is date parse in sql?

The date function used to parse a date or datetime value, according to a given format string. A wide variety of parsing options are available.


1 Answers

The code logic is fine, you only need java.sql.Timestamp instead of java.sql.Date. The SQL timestamp represents both the date and time parts, like date in Java. The SQL date represents only the date part.

See also:

  • Handling timestamps in MySQL using JDBC

Noted should be that you should prefer java.util.Date over java.sql.Timestamp in the model objects and use the Timestamp only at the very moment when you're about to set it in a SQL query. This separates the model objects from the JDBC API and improves their portability and reusability.

like image 64
BalusC Avatar answered Sep 19 '22 01:09

BalusC