2014-01-21 33 views
3

有一個表格有一個國家下拉菜單,用戶將選擇國家,然後有一個時區下拉菜單,用戶將選擇國家可用的時區然後用戶輸入本地日期(例如:2014年12月26日)和時間(23:11)(24小時時間),輸入日期和時間用於所選國家和時區。 現在我必須將此日期和時間轉換爲GMT時區。我怎樣才能做到這一點使用喬達時間使用約達時間將一個時區轉換爲另一個時區

如何計算夏令時(DST)?

我已經作出,其接受的參數作爲從時區到時區的功能,日期

public static String convertTimeZones(String fromTimeZoneString, 
      String toTimeZoneString, String fromDateTime) { 
     DateTimeZone fromTimeZone = DateTimeZone.forID(fromTimeZoneString); 
     DateTimeZone toTimeZone = DateTimeZone.forID(toTimeZoneString); 
     DateTime dateTime = new DateTime(fromDateTime, fromTimeZone); 

     DateTimeFormatter outputFormatter 
      = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm").withZone(toTimeZone); 
     return outputFormatter.print(dateTime); 
    } 

我想通過日期這個函數的格式(24-FEB-2014 12: 34)但它沒有采取這種格式

+2

看看[這個答案](http://stackoverflow.com/a/19003544/377628)。 – Hassan

+0

在這個鏈接我不明白任何東西,根據我的要求,我必須通過國家時區也是用戶已選擇 – user2841408

+0

可能的重複[解析日期與Joda API](http://stackoverflow.com/問題/ 20098644 /解析最新與 - 喬達-API) –

回答

4
//so we can get the local date 
//UTC = true, translate from UTC time to local 
//UTC = false, translate from local to UTC 

public static String formatUTCToLocalAndBackTime(String datetime, boolean UTC) { 
    String returnTimeDate = ""; 
    DateTime dtUTC = null; 
    DateTimeZone timezone = DateTimeZone.getDefault(); 
    DateTimeFormatter formatDT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 
    DateTime dateDateTime1 = formatDT.parseDateTime(datetime); 
    DateTime now = new DateTime(); 
    DateTime nowUTC = new LocalDateTime(now).toDateTime(DateTimeZone.UTC); 
    long instant = now.getMillis(); 
    long instantUTC = nowUTC.getMillis(); 
    long offset = instantUTC - instant; 

    if (UTC) { 
     //convert to local time 
     dtUTC = dateDateTime1.withZoneRetainFields(DateTimeZone.UTC); 
     //dtUTC = dateDateTime1.toDateTime(timezone); 
     dtUTC = dtUTC.plusMillis((int) offset); 
    } else { 
     //convert to UTC time 
     dtUTC = dateDateTime1.withZoneRetainFields(timezone); 
     dtUTC = dtUTC.minusMillis((int) offset);   
    } 

    returnTimeDate = dtUTC.toString(formatDT); 



    return returnTimeDate; 
} 
相關問題