Timezone conversion

后端 未结 12 1545
一向
一向 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:16

    If you don't want to use Joda, here is a deterministic way using the built in libraries.

    First off I recommend that you force your JVM to default to a timezone. This addresses the issues you might run into as you move your JVM from one machine to another that are set to different timezones but your source data is always a particular timezone. For example, lets say your data is always PDT/PST time zone, but you run on a box that is set to UTC timezone.

    The following code snippet sets the default timezone in my JVM:

     //You can either pass the JVM a parameter that 
     //enforces a TZ: java -Duser.timezone=UTC or you can do it
     //programatically like this
     TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
     TimeZone.setDefault(tz);
    

    Now lets say your source date is coming in as PDT/PST but you need to convert it to UTC. These are the steps:

        DateFormat dateFormatUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormatUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
    
        String dateStrInPDT = "2016-05-19 10:00:00";
        Date dateInPDT = dateFormat.parse(dateStrInPDT);
    
    
        String dateInUtc = dateFormatUtc.format(dateInPDT);
    
        System.out.println("Date In UTC is " + dateInUtc);
    

    The output would be:

    Date In UTC is 2016-05-19 17:00:00
    

提交回复
热议问题