将`Java.lang.String`转换为`oracle.sql.TIMESTAMPTZ`

时间:2016-04-28 10:27:49

标签: java oracle11g timezone simpledateformat timestamp-with-timezone

我有以下Java.lang.String个值,代表String TIMESTAMPTZ的值。我需要将这些Java.lang.String转换为oracle.sql.TIMESTAMPTZ

"2016-04-19 17:34:43.781 Asia/Calcutta",
"2016-04-30 20:05:02.002 8:00",
"2003-11-11 00:22:15.0 -7:00",
"2003-01-01 02:00:00.0 -7:00",
"2007-06-08 15:01:12.288 Asia/Bahrain",
"2016-03-08 17:17:35.301 Asia/Calcutta",
"1994-11-24 11:57:17.303"

我通过多种方式尝试过它。

样本1:

使用SimpleDateFormat

尝试
String[] timeZoneValues = new String[]{"2016-04-19 17:34:43.781 Asia/Calcutta", "2016-04-30 20:05:02.002 8:00", "2003-11-11 00:22:15.0 -7:00", "2003-01-01 02:00:00.0 -7:00", "2007-06-08 15:01:12.288 Asia/Bahrain", "2016-03-08 17:17:35.301 Asia/Calcutta", "1994-11-24 11:57:17.303"};
        for(String timeZoneValue: timeZoneValues){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
            try {
                simpleDateFormat.parse(timeZoneValue);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

抛出异常:

java.text.ParseException: Unparseable date: "2016-04-19 17:34:43.781 Asia/Calcutta"
    at java.text.DateFormat.parse(DateFormat.java:357)

样本2:

通过将这些String值直接转换为Timestamporacle.sql.TIMESTAMPTZ

来尝试
String parse = "2016-04-19 17:34:43.781 8:00";
        try {
            Timestamp timestamp = Timestamp.valueOf("2016-04-19 17:34:43.781 8:00");
        }catch (Exception ex){
            ex.printStackTrace();
        }

例外:

java.lang.NumberFormatException: For input string: "781 8:000"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at java.sql.Timestamp.valueOf(Timestamp.java:253)

样本3:

String parse = "2016-04-19 17:34:43.781 Asia/Calcutta";
DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis();
DateTime dateTime = dateTimeFormatter.parseDateTime(parse);
Timestamp timeStamp = new Timestamp(dateTime.getMillis());

例外:

Invalid format: "2016-04-19 17:34:43.781 Asia/Calcutta" is malformed at " 17:34:43.781 Asia/Calcutta"

样本4:

try {
TIMESTAMPTZ timestamptz = new TIMESTAMPTZ(connection, (String) colValue);
}catch (Exception ex){
ex.printStackTrace();
}

例外:

java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
    at java.sql.Timestamp.valueOf(Timestamp.java:249)
    at oracle.sql.TIMESTAMPTZ.toBytes(TIMESTAMPTZ.java:1919)
    at oracle.sql.TIMESTAMPTZ.<init>(TIMESTAMPTZ.java:253)

我正在尝试使用TIMESTAMPTZOracle值插入Apache Metamodel数据库,并在我的系统上安装了Java 1.7

3 个答案:

答案 0 :(得分:2)

您的时间戳不是标准的java可解析格式。因此,为了解析它们,您需要编写用于处理此类格式的自定义代码。

  

观察结果:

     

亚洲/加尔各答不是一个有效的Parseable TimeZone,因此你需要一些   获得相应时区的机制。

     

8:00也不是java中有效的Parseable Timezone,因此您需要   某种机制将其格式化为有效值+08:00

牢记以上几点,以下代码将为您提供所需。

    SimpleDateFormat dateFormatTZGeneral = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
    SimpleDateFormat dateFormatTZISO = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
    SimpleDateFormat dateFormatWithoutTZ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");


    String[][] zoneStrings = DateFormatSymbols.getInstance().getZoneStrings();

    Date date = null;

    String[] timeStampSplits = timestamp.split(" ");
    if(timeStampSplits.length>2) {

        String timezone = timeStampSplits[2];
        //First Case Asia/Calcutta
        if(Character.isAlphabetic(timezone.charAt(timezone.length()-1))) {

            for(String[] zoneString: zoneStrings) {
                if(zoneString[0].equalsIgnoreCase(timezone)) {
                    timeStampSplits[2] = zoneString[2];
                    break;
                }
            }

            timestamp = createString(timeStampSplits," ");
            date = getDate(timestamp, dateFormatTZGeneral);
        } else {
            //Second Case 8:00
            timeStampSplits[2] = formatTimeZone(timeStampSplits[2]);

            timestamp = createString(timeStampSplits," ");
            date = getDate(timestamp, dateFormatTZISO);
        }

    } else {
        // Third Case without timezone
        date = getDate(timestamp, dateFormatWithoutTZ);
    }

    System.out.println(date);

    TIMESTAMPTZ oraTimeStamp = new TIMESTAMPTZ(<connection object>,new java.sql.Timestamp(date.getTime());

以上代码使用以下实用程序方法

private static Date getDate(String timestamp, SimpleDateFormat dateFormat) {
    Date date = null;
    try {
        date = dateFormat.parse(timestamp);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return date;
}

private static String createString(String[] contents, String separator) {
    StringBuilder builder = new StringBuilder();
    for (String content : contents) {
        builder.append(content).append(separator);
    }
    builder.deleteCharAt(builder.length()-separator.length());

    return builder.toString();
}

private static String formatTimeZone(String timeZone) {
    String[] timeZoneSplits = timeZone.split(":");
    DecimalFormat formatter = new DecimalFormat("+##;-#");
    formatter.setMinimumIntegerDigits(2);

    timeZoneSplits[0] = formatter.format(Integer.parseInt(timeZoneSplits[0]));
    return createString(timeZoneSplits, ":");
}

此代码专门用于满足您的时间戳示例,任何偏差都可能无法处理,并且需要进行更多自定义。

希望这会对你有所帮助。

答案 1 :(得分:1)

您必须根据即将生成的数据解析日期。有关Android使用的常量的信息,您必须遵循link 如果是Java,您必须关注link 这是一些不同格式的代码片段 样本1

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzzz");
    Date date = null;
    try {
        date = sdf.parse("2016-04-19 17:34:43.781 Pacific Standard Time");
        Log.e("date",""+date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    sdf.setTimeZone(TimeZone.getTimeZone("IST"));
    System.out.println(sdf.format(date));

样本2

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
    Date date = null;
    try {
        date = sdf.parse("2016-04-19 17:34:43.781 -08:00");
        Log.e("date",""+date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    sdf.setTimeZone(TimeZone.getTimeZone("IST"));
    System.out.println(sdf.format(date));

样本3

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Date date = null;
    try {
        date = sdf.parse("2016-04-19 17:34:43.781");
        Log.e("date",""+date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    sdf.setTimeZone(TimeZone.getTimeZone("IST"));
    System.out.println(sdf.format(date));

因此,根据这三组样本,您可以解析任何类型的日期时间,除了一种格式,即&#34; 2016-04-19 17:34:43.781亚洲/加尔各答&#34;因为时区亚洲/加尔各答或亚洲/巴林无法通过android或java读取。根据我的理解,这是PHP支持的格式。所以如果你想解析这些类型的格式,那么我想你必须编写自定义的SimpleDateFormat,并且必须根据需要识别这些内容并执行计算。

答案 2 :(得分:0)

时间戳字符串格式不同,

 Ex-Here SimpleDateFormat uses pattern :
 'yyyy-MM-dd HH:mm:ss.SSS XXX'

where X is to represent timezone in [ISO 8601 time zone][1] format.For this      
timezone valid Timestamp Strings are (-08; -0800; -08:00).So,'Asia/Kolkata' 
will not be parsed for Sample 1.

There are three type of Timezone pattern to be assigned to SimpleDateFormat.
**'Z'** - RFC 822 time zone.
**'z'** - General time zone.
**'X'** - ISO 8601 time zone.

因此,要么使用不同的SimpleDateFormat,要么将所有时间戳的时区转换为相同的时区模式,并使用单个SimpleDateFormat。