Timezone conversion

后端 未结 12 1606
一向
一向 2020-11-22 11:25

I need to convert from one timezone to another timezone in my project.

I am able to convert from my current timezone to another but not from a different timezone to

12条回答
  •  礼貌的吻别
    2020-11-22 12:08

    You could use the java.time.ZoneDateTime#ofInstant() method:

    import java.time.*;
    
    public class TimeZonesConversion {
        static ZonedDateTime convert(ZonedDateTime time, ZoneId newTimeZone) {
            return ZonedDateTime.ofInstant(
                    time.toInstant(),
                    newTimeZone);
        };
    
        public static void main(String... args) {
            ZonedDateTime mstTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("-07")); 
            ZonedDateTime localTime = convert(mstTime, Clock.systemDefaultZone().getZone());
            System.out.println("MST(" + mstTime + ") = " + localTime);
        }
    }
    

提交回复
热议问题