首页 > 解决方案 > 中国Unix时间

问题描述

我正在尝试获取中国的当地时间。我从 worldtimeapi.org 网站获得了 unixTimeStamp。

问题:我得到的是当地时间而不是中国时间。

private class BackgroundProcess extends AsyncTask<Void, Void, String> {




    @Override
    protected String doInBackground(Void... voids) {
        String value = null;
        HttpHandler httpHandler = new HttpHandler();
        // Making a request to url and getting response
        String url = "http://worldtimeapi.org/api/timezone/Asia/Shanghai";

        String jsonStr = httpHandler.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

               value = jsonObj.getString("unixtime");

                Log.e(TAG, "Operation Okay: " + "\n\n"+value);

            } catch (final JSONException e) {

                Log.e(TAG, "Json parsing error: " + e.getMessage());



            }

        } else {
            Log.e(TAG, "Couldn't get json from server.");

        }

        return value ;





    }

    @Override
    protected void onPostExecute(String aVoid) {
        super.onPostExecute(aVoid);

        Toast.makeText(Timer_FullTime.this, aVoid, Toast.LENGTH_SHORT).show();

        long l = Long.valueOf(aVoid);
        long milliSec = l * 1000 ;



        SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a dd/MM/yyyy");
        String dateString = formatter.format(new Date(milliSec));
        currentTime.setText("" + dateString);
    }
}

我不明白为什么我现在不能得到 6:30 左右的中国时间,而我现在一直得到 3:54 左右的当地时间。

提前致谢

标签: javasimpledateformatunix-timestampworldtimeapi

解决方案


避免遗留的日期时间类

永远不要使用SimpleDateFormatDate。这些可怕的类在几年前被JSR 310 中定义的现代java.time类所取代。

java.time

您似乎得到一个长整数,表示自 1970 UTC 第一时刻的纪元参考以来的整秒数。

如果是这样,则解析为Instant.

Instant instant = Instant.ofEpochSeconds( seconds ) ;

通过应用 a 来从 UTC 调整到您的特定时区ZoneId以获取ZonedDateTime.

ZoneId z = ZoneId.of( "Asia/Shanghai" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

对于较旧的 Android,请参阅 Threeten-Backport 和 ThreeTenABP 项目。

所有这一切已经被覆盖了很多次。在发布之前搜索 Stack Overflow。


推荐阅读