Convert Date/Time for given Timezone - java

前端 未结 16 2499
孤城傲影
孤城傲影 2020-11-22 12:36

I want to convert this GMT time stamp to GMT+13:

2011-10-06 03:35:05

I have tried about 100 different combinations of DateFormat, TimeZone,

16条回答
  •  星月不相逢
    2020-11-22 12:54

    Understanding how computer time works is very important. With that said I agree that if an API is created to help you process computer time like real time then it should work in such a way that allows you to treat it like real time. For the most part this is the case but there are some major oversights which do need attention.

    Anyway I digress!! If you have your UTC offset (better to work in UTC than GMT offsets) you can calculate the time in milliseconds and add that to your timestamp. Note that an SQL Timestamp may vary from a Java timestamp as the way the elapse from the epoch is calculated is not always the same - dependant on database technologies and also operating systems.

    I would advise you to use System.currentTimeMillis() as your time stamps as these can be processed more consistently in java without worrying about converting SQL Timestamps to java Date objects etc.

    To calculate your offset you can try something like this:

    Long gmtTime =1317951113613L; // 2.32pm NZDT
    Long timezoneAlteredTime = 0L;
    
    if (offset != 0L) {
        int multiplier = (offset*60)*(60*1000);
        timezoneAlteredTime = gmtTime + multiplier;
    } else {
        timezoneAlteredTime = gmtTime;
    }
    
    Calendar calendar = new GregorianCalendar();
    calendar.setTimeInMillis(timezoneAlteredTime);
    
    DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
    
    formatter.setCalendar(calendar);
    formatter.setTimeZone(TimeZone.getTimeZone(timeZone));
    
    String newZealandTime = formatter.format(calendar.getTime());
    

    I hope this is helpful!

提交回复
热议问题