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

查看:51
本文介绍了将 Java 字符串转换为 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 或 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 字符串转换为 sql.Timestamp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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