fudy
fudy

Reputation: 1629

Convert String to Timestamp

Our customer will send us request including timestamp String likes : "2013-10-27T13:00:00.325234Z". I will use it to compare timestamp in oracle database.

how to convert the above String to java.sql.Timestamp?

I can convert it to Date, but Date only has the milliseconds precision.

Should keep the microseconds and timezone. thanks in advance.

Upvotes: 2

Views: 19832

Answers (6)

Anonymous
Anonymous

Reputation: 86379

Java 8

    String timestampString = "2013-10-27T13:00:00.325234Z";
    Instant inst = Instant.parse(timestampString);

Don’t use the Timestamp class if you can avoid it. To save the timestamp from the string, just pass the Instant to your PreparedStatement using its setObject method. It requires JDBC version 4.2 or higher. You probably have that already, or you should be able to get such a driver. You may also pass the Instant to a modern JPA implementation.

Parsing works without any explicit formatter because your string is in ISO 8601 format, the format that the modern java date and time classes parse (and also print) as their default.

The Timestamp class is long outdated. If you still need a Timestamp, for example for a legacy API that you cannot change or don’t want to change just now, the conversion is easy:

    Timestamp ts = Timestamp.from(Instant.parse(timestampString));

Java 6 and 7

Add ThreeTen Backport to your project (link below). Use the following imports.

import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.Instant;

Then do:

    Instant inst = Instant.parse(timestampString);
    Timestamp ts = DateTimeUtils.toSqlTimestamp(inst);

Links

Upvotes: 7

user8283048
user8283048

Reputation: 21

For me the String format was not yyyy-MM-dd HH:mm:ss.SSSSSS. So Timestamp.valueOf didn't work. So, I did like this

String s = "2017-12-29-05.04.18.104071";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss");//Yes, it works without .SSSSSS
Timestamp ts = new Timestamp(sdf.parse(s).getTime());
ts.setNanos(Integer.valueOf(s.substring(20)) * 1000);
System.out.println(ts.toString());

Upvotes: 0

RealSkeptic
RealSkeptic

Reputation: 34648

This is a Java 8 solution. It relies on the java.time library.

String isoStamp = "2013-10-27T13:00:00.325234Z";
OffsetDateTime odt = OffsetDateTime.parse(
                             isoStamp,
                             DateTimeFormatter.ISO_OFFSET_DATE_TIME );

The OffsetDateTime is a date-time object that has a precision of nanoseconds, and includes the offset from UTC. And the ISO_OFFSET_DATE_TIME is a standard DateTimeFormatter format, that understands the Z designation and sets it as offset 0 from UTC.

The next step is to use this in JDBC, and Oracle says in this article that the java.time objects should be used with the setObject() method (rather than setTimeStamp()). E.g.

stmt.setObject( 1, odt, JDBCType.TIMESTAMP_WITH_TIMEZONE );

Note that this may depend on the database and JDBC driver, which should, of course, be up-to-date.

Upvotes: 4

T.Gounelle
T.Gounelle

Reputation: 6033

[with Java8] If the format is strictly specified and you want a robust solution, use java.time.DateTimeFormatter to parse the date into a java.time.LocalDateTime that handles fraction of seconds down to the nanos and then you can create the java.sql.Timestamp:

public static void main(String[] args) throws ParseException {
    String line = "2013-10-27T13:00:00.325234Z";
    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
    LocalDateTime time = LocalDateTime.parse(line, dateFormat);
    Timestamp ts = Timestamp.valueOf(time);
    System.out.println(ts);
}

prints

2013-10-27 13:00:00.325234

Upvotes: -1

Sindhoo Oad
Sindhoo Oad

Reputation: 1194

what ever format you have define it in SimpleDate format , convert it to date and then convert it to Timestamp.

public static Timestamp stringToTimeStamp(String strTime){
    Timestamp tempTimestamp = null;
    if(strTime!=null && !strTime.equals(""))
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd");//format of date and time you have

        Date parsedTimeStamp = null;
        try {
            parsedTimeStamp = dateFormat.parse(strTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        tempTimestamp = new Timestamp(parsedTimeStamp.getTime());


    }
    return tempTimestamp;
}

Upvotes: -1

khelwood
khelwood

Reputation: 59222

Apart from the T in the middle and the Z at the end, you could pass it into Timestamp.valueOf(String).

So you could just have:

String line = "2013-10-27T13:00:00.325234Z";
Timestamp ts = Timestamp.valueOf(line.replace("T"," ").replace("Z",""));

This gives a timestamp matching

2013-10-27 13:00:00.325234

Upvotes: 9

Related Questions