2016-07-22 91 views
1

美好的一天。我正在建立一個聊天應用程序。爲了達到目的,我決定把信息的日期發送出去。沒有在不同國家的日期必須顯示不同的信息。例如我們帶兩個不同的國家,假設它們之間的差別是2小時.CountryX和CountryY。用戶從CountryX發送消息,時間可以說是15:00。我將這個保存在服務器上,具有用戶發送的確切時區時間,正好15 :00 as CountryX.Second用戶從CountryX接收2小時內CountryY的消息,所以基本上我必須在CountryY中顯示的時間必須是17:00。這是問題。我如何將已經接收的時間與已知的時區到當地爲了顯示正確?我做了很多谷歌,但所有我想出了,解決方案,你只需要得到一個確切的國家的時間,而不是轉換CountryX發送T ime到CountryY當地時間,以便正確顯示在CountryY.Please你能提供幫助嗎?非常感謝你事先。將接收的日期時間轉換爲本地時區時間Android

+0

退房lib目錄下:PrettyTime它適合聊天和當地時區 –

+0

好會chec現在看看它會給出 –

+0

似乎我找不到所需的方法 –

回答

-1

給大家,因爲this.I的苦難已經結束了我自己的邏輯創建我自己的類,它完美的作品,並作爲額外的獎勵一些方便的方法與時間稱爲

public class Time { 
    public static String getCurrentTime() { 
     Calendar calendar = Calendar.getInstance(); 
     int year = calendar.get(Calendar.YEAR); 
     int month = calendar.get(Calendar.MONTH) + 1; 
     int day = calendar.get(Calendar.DAY_OF_MONTH); 
     int hour = calendar.get(Calendar.HOUR_OF_DAY); 
     int minute = calendar.get(Calendar.MINUTE); 
     int second = calendar.get(Calendar.SECOND); 
     String finalFormat = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; 
     if (month < 10) { 
      String finalMonth = "0" + month; 
      finalFormat = year + "-" + finalMonth + "-" + day + " " + hour + ":" + minute + ":" + second; 
     } 

     return finalFormat; 
    } 

    public static String convertToLocalTime(String timeToConvert) { 
     SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     sourceFormat.setTimeZone(TimeZone.getTimeZone(Constants.SERVER_TIME_ZONE));//where server time zone is the time zone of your server as defauul,E.X -America/Los_Angeles 
     Date parsed; 
     try { 
      parsed = sourceFormat.parse(timeToConvert); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
      return ""; 
     } 

     TimeZone tz = TimeZone.getDefault(); 
     SimpleDateFormat destFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
     destFormat.setTimeZone(tz); 

     String result = destFormat.format(parsed); 
     return result; 
    } 

    public static String getTimeZone() { 
     return TimeZone.getDefault().getID(); 
    } 
} 
相關問題