将Java String转换为sql.Timestamp [英] Convert Java String to sql.Timestamp

查看:1045
本文介绍了将Java String转换为sql.Timestamp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下格式输入字符串:YYYY-MM-DD-HH.MM.SS.NNNNNN时间戳来自DB2数据库。我需要将它解析为java.sql.Timestamp并且不会丢失任何精度。到目前为止,我一直无法找到解析远远超过微秒的现有代码。 SimpleDateFormat返回Date并仅解析为毫秒。简短地看着JodaTime,并没有看到那也行。

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.

推荐答案

您是否尝试过使用 Timestamp.valueOf(String) ?它看起来应该几乎你想要的东西 - 你只需要将日期和时间之间的分隔符更改为空格,将小时和分钟之间的分隔符,以及分钟和小时之间的分隔符更改为冒号:

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

或者,通过获取子字符串并使用Joda Time或<解析为毫秒code> SimpleDateFormat (我非常喜欢Joda Time,但你的里程可能会有所不同)。然后将字符串的其余部分作为另一个字符串,并使用 Integer.parseInt 进行解析。然后,您可以非常轻松地组合这些值:

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

这篇关于将Java String转换为sql.Timestamp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆