2013-04-02 21 views
22

Ho un oggetto JSON, che hanno un campo che è una data di nascita:Come ottenere una data da un oggetto JSON

JSONObject obj = new JSONObject(response); 
User user = new User(); 
user.setuserID(obj.getString("userID")); 
user.setisMale(obj.getBoolean("isMale")); 
user.setEmail(obj.getString("email")); 
// user.setBirthdate(obj.getDate("birthdate")); 
user.setLastName(obj.getString("lastName")); 
user.setFirstName(obj.getString("firstName")); 

Ma il metodo getDate() non esiste in JSONObject.
Come posso impostare la data di nascita nell'oggetto Utente?

+1

Come è la data rappresentato nella risposta JSON? Immagino una stringa? Mostra il JSON. –

+0

È come: "data di nascita": "2012-08-01" – user2144555

risposta

37

Si può fare come qui di seguito,

String dateStr = obj.getString("birthdate"); 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date birthDate = sdf.parse(dateStr); 
//then 
user.setBirthdate(birthDate); 

speriamo di aiutare voi :)

+0

Risultato, ma stampa' Wed Aug 01 00:00:00 BST 2012', anche il mio formato è 'SimpleDateFormat (" yyyy-MM-dd ")' – user2144555

+0

il risultato è normale, perché il formato partten è "aaaa-MM-gg", per favore usa "aaaa-MM-gg HH: mm: ss" per ottenere ore, minuti e secondi. –

+0

@ Bob.Z Ricevo una stringa di date come questa "2015-12-25 00:00:00" voglio formattare come "2015-12-25 00:00:00 UTC". quale formato dovrei scrivere nel 'SimpleDateFormat ("? ")'. –

4

In generale, una data viene passata come millisecondo o come stringa formattata. Quindi, a seconda del vostro JSON è possibile utilizzare utilizzare new Date(json.getLong(milliseconds)) o se la data è nella stringa

String birthdate = json.getString(date);//"2013-03-26" 
DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
+0

Ne è risultato, ma è in stampa 'Wed Aug 01 00:00:00 BST 2012', anche il mio formato è' SimpleDateFormat ("yyyy-MM-dd") ' – user2144555

Problemi correlati