How to get a Date from a JSON object
Asked Answered
G

2

33

I have a JSON object, which have one field that is a birthdate:

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"));

But the method getDate() does not exist in JSONObject.
How can I set the Birthdate in my User object?

Gamopetalous answered 2/4, 2013 at 9:53 Comment(2)
How is your date represented in the JSON response? I guess a String? Show the JSON.Posse
It's like: "birthdate":"2012-08-01"Gamopetalous
S
51

You may do like below,

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

Hope to help you :)

Slinky answered 2/4, 2013 at 10:6 Comment(4)
It resulted, but it is printing Wed Aug 01 00:00:00 BST 2012, even my format is SimpleDateFormat("yyyy-MM-dd")Gamopetalous
your result is normal, because the format partten is "yyyy-MM-dd", please use "yyyy-MM-dd HH:mm:ss" to get hours, minutes and seconds.Slinky
@Bob.Z I am getting date string like this "2015-12-25 00:00:00" i want to format like this "2015-12-25 00:00:00 UTC". which format should i write in the SimpleDateFormat("?").Elkins
I would prefer the onliner new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(dateStr)Atropos
P
4

In general, a date is passed as milliseconds or as a formatted string. So depending upon your json you can use either use new Date(json.getLong(milliseconds)) or if date is in string

String birthdate = json.getString(date);//"2013-03-26"
DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
Pigmy answered 2/4, 2013 at 9:57 Comment(1)
It resulted, but it is printing Wed Aug 01 00:00:00 BST 2012, even my format is SimpleDateFormat("yyyy-MM-dd")Gamopetalous

© 2022 - 2024 — McMap. All rights reserved.