1

I am trying to convert a string which is in the format " 01/02/2018 02:48:04 PM " to a smalldatetime format to insert into MS SQL.

import java.sql.Date;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;

public class TimeStampTest {

    public static void main(String[] args) {
        String originalDate ="01/02/2018 02:29:23 PM";
        System.out.println(convertToSmallDatetimeFormat(originalDate));
    }

    private static Timestamp convertToSmallDatetimeFormat(String originalDate) {


        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendPattern("MM/dd/yyyy hh:mm:ss a")
                .toFormatter(Locale.US);
        LocalDateTime localDate = LocalDateTime.parse(originalDate,formatter);

        return new Timestamp(localDate.getNano()/1000000);

    }

}

But I realized that when I do the following code

LocalDateTime localDate = LocalDateTime.parse(originalDate,formatter);

I am getting some garbage value 2018-01-02T15:58:04

which results in localDate.getNano() to be 0

Sai Haridass
  • 344
  • 2
  • 11
  • are you using joda library or java.time ? – Vikas Apr 19 '19 at 03:24
  • I am using java.time – Sai Haridass Apr 19 '19 at 03:30
  • In recent MS SQL JDBC drivers you should be able to use `LocalDateTime` directly. You may also want to read [the javadoc of `LocalDateTime.getNano()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDateTime.html#getNano()) to understand why it doesn't work like you expect. – Mark Rotteveel Apr 19 '19 at 06:27

3 Answers3

0

You can use Timestamp.valueOf

private static Timestamp convertToSmallDatetimeFormat(String originalDate) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("MM/dd/yyyy hh:mm:ss a")
            .toFormatter(Locale.US);
    LocalDateTime localDate = LocalDateTime.parse(originalDate,formatter);
    System.out.println("****"+localDate);
    return Timestamp.valueOf(localDate);
}
Vikas
  • 6,868
  • 4
  • 27
  • 41
0

To convert the string and insert it as smalldatetime you don't need to use java.sql.Timestamp at all. Simply pass the LocalDateTime object to PreparedStatement#setObject like this:

Statement st = conn.createStatement();
st.execute("CREATE TABLE #tmp (id int PRIMARY KEY, sdt smalldatetime)");

PreparedStatement ps = conn.prepareStatement("INSERT INTO #tmp (id, sdt) VALUES (?, ?)");
ps.setInt(1, 1);
String originalDate = "01/02/2018 02:29:43 PM";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern("MM/dd/yyyy hh:mm:ss a")
        .toFormatter(Locale.US);
LocalDateTime ldt = LocalDateTime.parse(originalDate, formatter);
System.out.println(ldt);  // 2018-01-02T14:29:43
ps.setObject(2, ldt);
ps.executeUpdate();

And, if you are using mssql-jdbc version 7.1.0 or later you can retrieve the values directly into a LocalDateTime object (I created the pull request for that feature)

ResultSet rs = st.executeQuery("SELECT sdt FROM #tmp WHERE id=1");
rs.next();
LocalDateTime retrieved = rs.getObject(1, LocalDateTime.class);
System.out.println(retrieved);  // 2018-01-02T14:30
// note that the minutes value is rounded
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
-1

You can actually do it from the MySQL query itself which may save you some time:

Depending on what version you use, this is for MariaDB

SELECT DATE_FORMAT(date, "%Y-%m-%d  %H:%M:%S") date FROM `table`
  • Microsoft SQL Server is not MySQL, and the OP wants to convert a string value in Java to an appropriate date to put in the database, not the other way around. – Mark Rotteveel Apr 19 '19 at 06:25