2016-02-13 71 views
0

我正在开发一个项目,我想将服务器时间转换为使用GMT的本地时间。 例如我的服务器在美国的密歇根州,我住在巴黎(法国),服务器时间是10:52,我想转换到我当地的时间16:52我使用下面的代码,似乎并不像工作。这转换时间使用GMT + 12而不是+6,我不知道为什么帮助我请!!!!!!将服务器时间转换为android的当地时间

public String GettingHeure(Context c, String date){ 
    SimpleDateFormat datechanged = new SimpleDateFormat("HH:MM", Locale.getDefault()); 
    Date dates = null; 
    String heureChanged = null; 
    try { 
     SimpleDateFormat formatter = new SimpleDateFormat("hh:mm",Locale.getDefault()); 
     dates = formatter.parse(date); 

     TimeZone tz = TimeZone.getDefault(); 
     formatter.setTimeZone(TimeZone.getTimeZone(tz.getID())); 

     System.out.println("local time : " + dates); 
     System.out.println("time in GMT : " + formatter.format(dates)); 
     //Toast.makeText(c.getApplicationContext(), "String : "+ date+" "+formatter.format(dates), Toast.LENGTH_LONG).show(); 
     heureChanged = formatter.format(dates); 
     SimpleDateFormat formatters = new SimpleDateFormat("hh:mm"); 

     Date datess = formatters.parse(heureChanged); 

     System.out.println("local time : " + datess); 
     System.out.println("time in GMT : " + formatters.format(datess)); 
     heureChanged = formatter.format(datess); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return heureChanged; 
+2

如果你从服务器获得了更普遍理解的格式的时间,比如“纪元”(1970年1月1日)以来的秒数或毫秒数,那将会好很多。在这种情况下,您不必解析字符串。 –

+0

谢谢我正在努力! –

回答

1

如果我正确理解你的问题,你想要在时区之间转换时间。这是执行该操作的代码。

public void convertDate(Date d) { 

    //You are getting server date as argument, parse your server response and then pass date to this method 

    SimpleDateFormat sdfAmerica = new SimpleDateFormat("hh:mm:ss"); 

    String actualTime = sdfAmerica.format(d); 
    //Changed timezone 
    TimeZone tzInAmerica = TimeZone.getTimeZone("CST"); 
    sdfAmerica.setTimeZone(tzInAmerica); 

    String convertedTime = sdfAmerica.format(d); 

    System.out.println("actual : " + actualTime + " converted " + ConvertedTime); 

    return convertedTime; 
    } 

希望这会有所帮助。

+0

谢谢我尝试从服务器获取日期对象,然后将其发送到android设备,然后setTimeZone它 –

+0

我已经更新代码,你会在Android端使用上述功能,并通过日期或时间作为参数,你从服务器 – sandip

+0

谢谢!有效! –

相关问题