我一直在分析我的天气数据我可以成功地提取描述,最低和最高温度,但日期是未知的格式如何处理日期将其转换为可读格式
"list":[
{
"dt":1497852000,
"temp":{
"day":301.14,
"min":294.81,
"max":301.14,
"night":294.81,
"eve":301.14,
"morn":301.14
},
"pressure":990.68,
"humidity":88,
"weather":[
{
"id":501,
"main":"Rain",
"description":"moderate rain",
"icon":"10d"
}我的代码:
public static void JSONParsing(String forecastJsonStr) throws JSONException {
double MinTemp;
double MaxTemp;
String Date,description;
JSONObject forecastDate = new JSONObject(forecastJsonStr);
JSONArray ForecastData = forecastDate.getJSONArray("list");
for(int i =0 ; i< ForecastData.length();i++){
JSONObject weather = ForecastData.getJSONObject(i);
JSONObject Data = weather.getJSONObject("temp");
JSONObject Description = weather.getJSONArray("weather").getJSONObject(0);
description = Description.getString("description");
MinTemp = Data.getDouble("min");
MaxTemp = Data.getDouble("max");
}
}发布于 2017-06-20 00:23:07
您的日期是seconds格式的long类型,因此请尽可能长时间地获取dt,然后将其与1000相乘,以将其转换为miliseconds,使用Date和SimpleDateFormat
1.)获取您的日期作为long
2.)将其传递给Date类构造函数,同时将其与1000相乘,以将秒转换为毫秒
3.)创建并应用SimpleDateFormat来获取日期
e.g
String s1 ="{\"dt\":1497852000}";
JSONObject jsonObject2 = new JSONObject(s1);
java.util.Date date = new java.util.Date(jsonObject2.getLong("dt")*1000);
SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yy");
String dateText = date_format.format(date);
System.out.println(dateText); 输出:
19/06/17注意:由于您的JSONResponse不完整,所以我只添加了一个简单的案例来演示您的问题
发布于 2017-06-20 02:21:25
你可以像这样格式化,
try {
JSONObject responseObject = new JSONObject(response);
JSONArray listJsonArray = responseObject.optJSONArray("list");
if (listJsonArray == null || listJsonArray.length() == 0) {
return;
}
for (int i = 0; i < listJsonArray.length(); i++) {
JSONObject eachDayJson = listJsonArray.optJSONObject(i);
if (eachDayJson == null) {
continue;
}
long dateInSeconds = eachDayJson.optLong("dt"); // Get date as seconds
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
String readableDate = format.format(new Date(dateInSeconds * 1000)); // convert that in milliseconds
}
} catch (JSONException e) {
e.printStackTrace();
}https://stackoverflow.com/questions/44635433
复制相似问题