java - 在android中将服务器时间转换为本地时间

标签 java android

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

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;

最佳答案

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

    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;
    }

希望这会有所帮助。

关于java - 在android中将服务器时间转换为本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35378221/

相关文章:

java - 创建 ApplicationContext 作为 Spring bean(通过其他应用程序上下文)

java - 将包添加到类路径时包不存在错误

java - 如何在 Java 中读取 .txt 文件中一行的最后一组数字

javascript - 无法使用不同用户的 HTML5 Geolocation 和 Android 获取位置

java - 在我的适配器中,我无法更改 onClickListener 中的定义值

android - 约束布局 : Unable to scale image to fit a ratio in RecyclerView

java - android.widget.LinearLayout 无法转换为 RecyclerView 中的 android.widget.TextView?

java.lang.IllegalStateException : ViewPager 错误

android - perf_event 用于进程中的多个线程

android - Android 2.3.3 中的 HTML 标签解析错误