我正在尝试获取中国的当地时间。我从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。
预先感谢
答案 0 :(得分:2)
请勿使用SimpleDateFormat
和Date
。几年前,这些糟糕的类被JSR 310中定义的现代 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项目。
所有这些已经被覆盖很多次了。发布前搜索堆栈溢出。