[英]JSON time format to Android time format
我的API給我這個結果:
{"time":{"Hours":0,"Minutes":0,"Seconds":0,"Milliseconds":0,"Ticks":0,"Days":0,"TotalDays":0,"TotalHours":0,"TotalMilliseconds":0,"TotalMinutes":0,"TotalSeconds":0}}
如何從Android中獲取hh:mm:ss格式?
所以....
例如:
{"time":{"Hours":12,"Minutes":11,"Seconds":23,"Milliseconds":0,"Ticks":0,"Days":0,"TotalDays":0,"TotalHours":0,"TotalMilliseconds":0,"TotalMinutes":0,"TotalSeconds":0}}
我在eclipse中編寫了此代碼,與Android完全相同。...
public static void main(String[] args) throws JSONException {
String jsonData = "";
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("/example.json"));
while ((line = br.readLine()) != null) {
jsonData += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
JSONObject object = new JSONObject(jsonData).getJSONObject("time");
int hour = object.getInt("Hours");
int min = object.getInt("Minutes");
int sec = object.getInt("Seconds");
System.out.println(hour + ":" + min + ":" + sec);
}
結果是...
12:11:23
嘗試這個
public void getFormatedDate(JSONObject object){
try {
JSONObject object1 = object.getJSONObject("time");
int hour = object1.getInt("Hour");
int minute = object1.getInt("Minutes");
int seconds = object1.getInt("Seconds");
int milis = object1.getInt("Milliseconds");
String time = hour+":"+minute+":"+seconds+":"+milis;
} catch (JSONException e) {
e.printStackTrace();
}
}
就那么簡單 -
String yourApiString = "";
try {
JSONObject jsonObject = new JSONObject(yourApiString); // Converts your API JSON string to JsonObject
JSONObject timeObject = jsonObject.getJSONObject("time"); // Fetch time object
int hours = timeObject.optInt("Hours"); // Fetches Hours integer
int minutes = timeObject.optInt("Minutes"); // Fetches Minutes integer
int seconds = timeObject.optInt("Seconds"); // Fetches Seconds integer
String time = hours + ":" + minutes + ":" + seconds; // Concatenate all values to get hh:mm:ss format
Log.d(TAG, "Time: " + time); // You will get time in hh:mm:ss
} catch (JSONException e) {
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.