2016-02-29 44 views
1

我發現很多功能從utc轉換到當地時間,但我沒有找到如何從本地轉換爲utc?如何從當地時間轉換爲utc?

這是從UTC用於當地,如何編輯從本地獲得UTC?

 public static String timezoneAwareDate(String date){ 
    // create simpledateformat for UTC dates in database 
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 

    Date output; 
    // parse time 
    try{ 
     output = simpleDateFormat.parse(date); 
    }catch (Exception e){ 
     // return current time 
     output = new Date(); 
    } 

    return output.toString(); 
} 
+0

看起來像這實際上讓你UTC時間。注意'.setTimeZone(TimeZone.getTimeZone( 「UTC」)' –

+4

http://stackoverflow.com/questions/17677546/utc-time-into-local-time-in-android –

+0

沒有,本地時間16:20是這裏是UTC + 2,所以UTC時間應該是14:20,但我發現它18:20 @TimCastelijns –

回答

0

將此類添加到您的項目中,並使用它們的方法將本地utc或utc應用到本地。

import java.util.TimeZone; 

public final class Utility { 
public static final TimeZone utcTZ = TimeZone.getTimeZone("UTC"); 

public static long toLocalTime(long time, TimeZone to) { 
    return convertTime(time, utcTZ, to); 
} 

public static long toUTC(long time, TimeZone from) { 
    return convertTime(time, from, utcTZ); 
} 

public static long convertTime(long time, TimeZone from, TimeZone to) { 
    return time + getTimeZoneOffset(time, from, to); 
} 

private static long getTimeZoneOffset(long time, TimeZone from, TimeZone to) { 
    int fromOffset = from.getOffset(time); 
    int toOffset = to.getOffset(time); 
    int diff = 0; 

    if (fromOffset >= 0){ 
     if (toOffset > 0){ 
      toOffset = -1*toOffset; 
     } else { 
      toOffset = Math.abs(toOffset); 
     } 
     diff = (fromOffset+toOffset)*-1; 
    } else { 
     if (toOffset <= 0){ 
      toOffset = -1*Math.abs(toOffset); 
     } 
     diff = (Math.abs(fromOffset)+toOffset); 
    } 
    return diff; 
    } 
} 

如果你想更多關於這件事。它已經在這個link

+1

雖然此代碼段可以解決的問題,[包括一個解釋](http://meta.stackexchange.com/questions/114762/explain-completely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – Ferrybig

+0

功能之外,'Utility'是一類一個非常模糊的名稱 –

+0

@TimCastelijns你是正確的,但這個類可以擴展更多的解決件事的方法。你有什麼建議,如姓名此類:) – slymnozdmrc

2
public static java.util.Date getConvertedDate(java.util.Date date,String newTimeZone) { 

    if(date != null) { 
     SimpleDateFormat df = new SimpleDateFormat("dd/MM/yy hh:mm a"); 
     df.setTimeZone(TimeZone.getTimeZone(newTimeZone)); 

     Calendar calendar = Calendar.getInstance(); 
     calendar.setTime(date); 

     String newdt = df.format(calendar.getTime()); 
     try { 
      date = df.parse(newdt); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
    } 
    return date; 
} 
+2

WELCOM e堆棧溢出!儘管這段代碼可以解決這個問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – Ferrybig

相關問題