如何在Android中将服务器时间转换为当前时间?

时间:2016-10-18 11:54:17

标签: android

try {
                    System.out.println("check response" + response);
                    JSONObject jsonobject = new JSONObject(response);
                    JSONObject jobojectsecond = jsonobject.getJSONObject("Data");
                    mcdetail = new MsgComments();
                    mcdetail.setId(jobojectsecond.getString("Id"));
                    mcdetail.setUsername(jobojectsecond.getString("UserName"));
                    mcdetail.setUserid(jobojectsecond.getString("UserId"));
                    mcdetail.setCommenttext(jobojectsecond.getString("CommentText"));
                    Comment = jobojectsecond.getString("CommentTime");


                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ssa", Locale.US);
                    TimeZone timeZone = TimeZone.getTimeZone("US/Eastern");
                    sdf.setTimeZone(timeZone);
                    String gmtStrDate = sdf.format(Calendar.getInstance().getTime());
                    System.out.println("GMT 1" + gmtStrDate);


                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ssa");
                    TimeZone timeZone1 = TimeZone.getTimeZone("GMT+5:30");
                    sdf1.setTimeZone(timeZone1);
                    Date gmtDate = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
                    String str21 = sdf1.format(gmtDate);
                    System.out.println("GMT 2" + str21);

我在Android中使用此代码转换日期格式我们从服务器接收日期此代码转换为我要转换的日历。

1 个答案:

答案 0 :(得分:0)

TimeZone fromTimezone =TimeZone.getTimeZone("US/Eastern");
TimeZone toTimezone=TimeZone.getTimeZone("Asia/Calcutta");

long fromOffset = fromTimezone.getOffset(calendar.getTimeInMillis());//Server date
long toOffset = toTimezone.getOffset(calendar.getTimeInMillis());

long convertedTime = calendar.getTimeInMillis() - (fromOffset - toOffset);
convertDate(convertedTime,"dd/MM/yyyy hh:mm:ss");

//Support function
public static String convertDate(String dateInMilliseconds,String dateFormat) {
    return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
}