Timezone conversion

后端 未结 12 1424
一向
一向 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:10
    public static String convertTimeBasedOnTimeZoneAndTimePattern(String dateTime,
      String fromTimeZone, String toTimeZone, String originalTimePattern, String timePattern) {
    
      DateTimeFormatter formatterNew = DateTimeFormatter.ofPattern(timePattern);
    
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern(originalTimePattern);
    
      TemporalAccessor temporalAccessor = formatter.parse(dateTime);
      ZoneId z = ZoneId.of(fromTimeZone);
      LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
      ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, z);
      Instant instant = Instant.from(zonedDateTime);
    
      ZonedDateTime fromZonedDateTime = instant.atZone(ZoneId.of(toTimeZone));
    
      String fromZoneDateTime = fromZonedDateTime.format(formatterNew);
    
    return fromZoneDateTime;}
    

    To convert any time to the specific timezone (for example: UTC -> local timezone and vise versa) with any time pattern you can use java.time library.

    This method will take time patterns (original and required format) and timezone (original time zone and required timezone) will give String as output. you can convert String to date by using SimpleDateFormatter or also use parse method of the ZoneDateTime/Instant class.

    To convert String to date:

    public static final DATE_FORMAT="yyyy-MM-dd HH:mm:ss.SSSSS";
    public static Date convertStringToDate(String date) {
        SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
    
        Date parsedDate = null;
    
        try {
          parsedDate = formatter.parse(date);
        } catch (Exception e) {
          throw new DateTimeParseException("Please provide date time in proper format", null, 0, null);
        }
        return parsedDate;
      }
    

    To convert date to String:

    public String convertTextDateToDate(Date textDate) {
        // SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", //Locale.ENGLISH);
    
        SimpleDateFormat date = new SimpleDateFormat(DATE_FORMAT);
        String dateFormatted = date.format(textDate);
        return dateFormatted;
      }
    
    0 讨论(0)
  • 2020-11-22 12:13

    Some examples

    Convert time between timezone

    Converting Times Between Time Zones

    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.TimeZone;
    
    public class TimeZoneExample {
        public static void main(String[] args) {
            // Create a calendar object and set it time based on the local
            // time zone
            Calendar localTime = Calendar.getInstance();
            localTime.set(Calendar.HOUR, 17);
            localTime.set(Calendar.MINUTE, 15);
            localTime.set(Calendar.SECOND, 20);
    
            int hour = localTime.get(Calendar.HOUR);
            int minute = localTime.get(Calendar.MINUTE);
            int second = localTime.get(Calendar.SECOND);
    
    
            // Print the local time
            System.out.printf("Local time  : %02d:%02d:%02d\n", hour, minute, second);
    
    
            // Create a calendar object for representing a Germany time zone. Then we
            // wet the time of the calendar with the value of the local time
    
            Calendar germanyTime = new GregorianCalendar(TimeZone.getTimeZone("Europe/Berlin"));
            germanyTime.setTimeInMillis(localTime.getTimeInMillis());
            hour = germanyTime.get(Calendar.HOUR);
            minute = germanyTime.get(Calendar.MINUTE);
            second = germanyTime.get(Calendar.SECOND);
    
    
            // Print the local time in Germany time zone
            System.out.printf("Germany time: %02d:%02d:%02d\n", hour, minute, second);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 12:15

    tl;dr

    ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ))              // Current moment in a particular time zone.
                 .withZoneSameInstant( ZoneId.of( "Asia/Kolkata" ))  // Same moment adjusted into another time zone. 
    

    Details

    The java.util.Date class has no time zone assigned, yet it's toString implementation confusingly applies the JVM's current default time zone.

    Avoid java.util.Date & .Calendar

    This is one of many reasons to avoid the notoriously troublesome java.util.Date, .Calendar, and SimpleDateFormat classes bundled with Java. Avoid them. Instead use either:

    • The java.time package built into Java 8 and inspired by Joda-Time.
    • Joda-Time

    java.time

    Java 8 and later has the java.time package built-in. This package was inspired by Joda-Time. While they share some similarities and class names, they are different; each has features the other lacks. One notable difference is that java.time avoids constructors, instead uses static instantiation methods. Both frameworks are led by the same man, Stephen Colbourne.

    Much of the java.time functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project. Further adapted to Android in the ThreeTenABP project.

    In the case of this Question, they work in the same fashion. Specify a time zone, and call a now method to get current moment, then create a new instance based on the old immutable instance to adjust for time zone.

    Note the two different time zone classes. One is a named time zone including all the rules for Daylight Saving Time and other such anomalies plus an offset from UTC while the other is only the offset.

    ZoneId zoneMontréal = ZoneId.of("America/Montreal"); 
    ZonedDateTime nowMontréal = ZonedDateTime.now ( zoneMontréal );
    
    ZoneId zoneTokyo = ZoneId.of("Asia/Tokyo"); 
    ZonedDateTime nowTokyo = nowMontréal.withZoneSameInstant( zoneTokyo );
    
    ZonedDateTime nowUtc = nowMontréal.withZoneSameInstant( ZoneOffset.UTC );
    

    Joda-Time

    Some example code in Joda-Time 2.3 follows. Search StackOveflow for many more examples and much discussion.

    DateTimeZone timeZoneLondon = DateTimeZone.forID( "Europe/London" );
    DateTimeZone timeZoneKolkata = DateTimeZone.forID( "Asia/Kolkata" );
    DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );
    
    DateTime nowLondon = DateTime.now( timeZoneLondon ); // Assign a time zone rather than rely on implicit default time zone.
    DateTime nowKolkata = nowLondon.withZone( timeZoneKolkata );
    DateTime nowNewYork = nowLondon.withZone( timeZoneNewYork );
    DateTime nowUtc = nowLondon.withZone( DateTimeZone.UTC );  // Built-in constant for UTC.
    

    We have four representations of the same moment in the timeline of the Universe.


    Actually the java.util.Date class does have a time zone buried within its source code. But the class ignores that time zone for most practical purposes. So, as shorthand, it’s often said that j.u.Date has no time zone assigned. Confusing? Yes. Avoid the mess that is j.u.Date and go with Joda-Time and/or java.time.

    0 讨论(0)
  • 2020-11-22 12:15

    You can do something like this to get the current time in another time zone.

    Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan"));
    japanCal.setTimeInMillis(local.getTimeInMillis());
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 12:20

    You can use the following code snippet

    String dateString = "14 Jul 2014 00:11:04 CEST";
    date = formatter.parse(dateString);
    System.out.println(formatter.format(date));
    
    // Set the formatter to use a different timezone - Indochina Time
    formatter.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
    System.out.println("ICT time : "+formatter.format(date));
    
    0 讨论(0)
提交回复
热议问题