将String转换为datetime(时区不同)并保存到数据库

时间:2016-01-27 02:33:20

标签: java

我将使用

接收数据时间
String format(eg: "2015-07-30-17.23.49.284526")

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

2 个答案:

答案 0 :(得分:0)

假设您正在使用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;}

答案 1 :(得分:0)

您需要知道输入字符串的zoneid,当前解决方案为ZonedDateTime java 8

您在瑞典的输入字符串是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);
}