49

Got a String coming in with this format: YYYY-MM-DD-HH.MM.SS.NNNNNN The Timestamp is coming from a DB2 database. I need to parse it into a java.sql.Timestamp and NOT lose any precison. So far I've been unable to find existing code to parse that far out to microseconds. SimpleDateFormat returns a Date and only parses to milliseconds. Looked at JodaTime briefly and didn't see that would work either.

5
  • 2
    If the timestamp comes from a DB2 database, why are you reading it as a string rather than read it as a Timestamp directly? Commented Oct 2, 2011 at 17:48
  • 1
    The timestamp is coming from the database and a client is returning it to us for a keyed read. Commented Oct 3, 2011 at 1:06
  • 1
    If you are using the timestamp for a keyed read, and you are presumably first sending it out to the client, you could alternatively consider converting it to an long of nanoseconds and then reading it back, instead of a string value. i.e. send out long l = ts.getTime() and then read it back with new Timestamp(l). You could even serialize this value to save space on the wire (but you'd lose human redability in this case). Commented Feb 5, 2014 at 8:56
  • What if my string is not in this format and rather in mm/dd/yyyy hh:mm format. This in this case how to convert to Timestamp format Commented Jun 30, 2014 at 10:05
  • UPDATE The new java.time package built into Java 8 handles nanosecond resolution. May be easier/better than dealing with java.sql.Timestamp depending on your scenario. You can convert to and from java.time & java.sql.Timestamp as well. Commented May 9, 2015 at 20:10

5 Answers 5

84

Have you tried using Timestamp.valueOf(String)? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:

import java.sql.*;

public class Test {
    public static void main(String[] args) {
        String text = "2011-10-02 18:48:05.123456";
        Timestamp ts = Timestamp.valueOf(text);
        System.out.println(ts.getNanos());
    }
}

Assuming you've already validated the string length, this will convert to the right format:

static String convertSeparators(String input) {
    char[] chars = input.toCharArray();
    chars[10] = ' ';
    chars[13] = ':';
    chars[16] = ':';
    return new String(chars);
}

Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat (I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt. You can then combine the values pretty easily:

Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();

Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);
Sign up to request clarification or add additional context in comments.

1 Comment

how does Timestamp.valueOf(String) handle the Timezone?
9

You could use Timestamp.valueOf(String). The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...], so you might need to change the field separators in your incoming string.

Then again, if you're going to do that then you could just parse it yourself and use the setNanos method to store the microseconds.

1 Comment

Timestamp.valueOf("2015/06/08".replaceAll("/", "-") + " 00:00:00")
8

Here's the intended way to convert a String to a Date:

String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);

Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.

3 Comments

This gives you java.util.Date and the request is for the creation of java.sql.Timestamp. It's also in Java, where the question asks for Scala.
You're right on the first point, but the question never mentioned Scala and is tagged Java. In fact, as far as I can tell, your comment is the only text on this entire page that even mentions Scala
Sorry about that, I got confused with another question that requested Scala explicitly. I’ll remove my down vote when they let me.
2

If you get time as string in format such as 1441963946053 you simply could do something as following:

//String timestamp;
Long miliseconds = Long.valueOf(timestamp);
Timestamp ti = new Timestamp(miliseconds);

1 Comment

But you don't get the date int his format, see the question.
1

I believe you need to do this:

  1. Convert everythingButNano using SimpleDateFormat or the like to everythingDate.
  2. Convert nano using Long.valueof(nano)
  3. Convert everythingDate to a Timestamp with new Timestamp(everythingDate.getTime())
  4. Set the Timestamp nanos with Timestamp.setNano()

Option 2 Convert to the date format pointed out in Jon Skeet's answer and use that.

Comments

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.