parsing with - Convert Java String to sql.Timestamp

timezone example (5)

Here's the intended way to do it:

String timestamp = "2011-10-02-";
DateFormat df = new SimpleDateFormat("");
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.

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.

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.

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);

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);

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);

Just use the appropriate method: String#split().

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that this takes a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

So, if you want to split on e.g. period/dot . which means "any character" in regex, use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

String[] parts = string.split(Pattern.quote(".")); // Split on period.

To test beforehand if the string contains certain character(s), just use String#contains().

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");

Note, this does not take a regular expression. For that, use String#matches() instead.

If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42

java string parsing timestamp