Unix时代对中国

问题描述 投票:-1回答:1

我想赶上中国的当地时间。我从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。

提前致谢

java simpledateformat unix-timestamp worldtimeapi
1个回答
2
投票

Avoid legacy date-time classes

切勿使用SimpleDateFormatDate。几年前,JSR 310中定义的现代java.time类取代了那些可怕的类。

java.time

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

如果是这样,解析为Instant

Instant instant = Instant.ofEpochSeconds( seconds ) ;

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.