Java 将字符串转换为日期时间(时区不同)并保存到数据库

Java 将字符串转换为日期时间(时区不同)并保存到数据库,java,Java,我将与您一起接收数据时间 String format(eg: "2015-07-30-17.23.49.284526") 并将其保存到oracle数据库中。但该值基于其他时区。如何将其转换为数据库特定值并基于本地时区?假设您使用的是joda time。如果没有。建议尝试使用它 检查代码是否适用于您: public static Timestamp convertStringToTimestampWithTimeZone(String fromTimeZone, String toTim

我将与您一起接收数据时间

String format(eg: "2015-07-30-17.23.49.284526")

并将其保存到oracle数据库中。但该值基于其他时区。如何将其转换为数据库特定值并基于本地时区?

假设您使用的是joda time。如果没有。建议尝试使用它

检查代码是否适用于您:

    public static Timestamp convertStringToTimestampWithTimeZone(String fromTimeZone, String toTimeZone, String input){
        String pattern = "yourdatetimeformat";
        DateTime dt  = DateTime.parse(input, DateTimeFormat.forPattern(pattern)).withZoneRetainFields(DateTimeZone
            .forID(fromTimeZone)).withZone(DateTimeZone.forID(toTimeZone));
        Timestamp ts = new Timestamp(dt.getMillis());
        return ts;}

您需要知道输入字符串的zoneid,即使用
ZoneDateTime
Java8的当前解决方案

您在瑞典的输入字符串为UTC+1

try {
    ZoneId fromZoneId = ZoneId.of("UTC+1");
    String input = "2015-07-30-17.23.49.284526";                    
    DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm.ss.SSSSSS");
    LocalDateTime dateTimeWithoutZone = LocalDateTime.parse(input, pattern);
    ZonedDateTime fromZonedDateTime = dateTimeWithoutZone.atZone(fromZoneId);
    ZonedDateTime localZonedDateTime = fromZonedDateTime.toInstant().atZone(ZoneId.systemDefault());                    
    System.out.println(localZonedDateTime.format(pattern));
} catch (Exception e) {
    e.printStackTrace(System.out);
}   

把它分开,然后做你想做的。毕竟,合并它们。字符串的时区是什么?字符串是由Sweden抱歉中的服务器生成的。我忘了提到我正在研究Java7。