Date and time conversion to some other Timezone in java

后端 未结 10 485
失恋的感觉
失恋的感觉 2020-12-11 21:13

i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i

10条回答
  •  清歌不尽
    2020-12-11 22:07

    2020 Answer Here

    If you want the new java.time.* feature but still want to mess with java.util.Date:

     public static Date convertBetweenTwoTimeZone(Date date, String fromTimeZone, String toTimeZone) {
            ZoneId fromTimeZoneId = ZoneId.of(fromTimeZone);
            ZoneId toTimeZoneId = ZoneId.of(toTimeZone);
    
            ZonedDateTime fromZonedDateTime =
                    ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).withZoneSameLocal(fromTimeZoneId);
    
            ZonedDateTime toZonedDateTime = fromZonedDateTime
                    .withZoneSameInstant(toTimeZoneId)
                    .withZoneSameLocal(ZoneId.systemDefault())
                    ;
    
            return Date.from(toZonedDateTime.toInstant());
        }
    

    for java.sql.Timestamp

        public static Timestamp convertBetweenTwoTimeZone(Timestamp timestamp, String fromTimeZone, String toTimeZone) {
    
            ZoneId fromTimeZoneId = ZoneId.of(fromTimeZone);
            ZoneId toTimeZoneId = ZoneId.of(toTimeZone);
    
            LocalDateTime localDateTimeBeforeDST = timestamp.toLocalDateTime();
    
            ZonedDateTime fromZonedDateTime = ZonedDateTime.of(localDateTimeBeforeDST, fromTimeZoneId);
    
            ZonedDateTime toZonedDateTime = fromZonedDateTime.withZoneSameInstant(toTimeZoneId);
    
            return Timestamp.valueOf(toZonedDateTime.toLocalDateTime());
        }
    

提交回复
热议问题