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?

ric
  • 627
  • 1
  • 12
  • 23
user2144555
  • 1,315
  • 11
  • 34
  • 55

2 Answers2

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 :)

Hunter Zhao
  • 4,589
  • 2
  • 25
  • 39
  • It resulted, but it is printing `Wed Aug 01 00:00:00 BST 2012`, even my format is `SimpleDateFormat("yyyy-MM-dd")` – user2144555 Apr 02 '13 at 10:11
  • 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. – Hunter Zhao Apr 02 '13 at 10:14
  • @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("?")`. – hasnain_ahmad Oct 09 '15 at 05:41
  • 1
    I would prefer the onliner new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(dateStr) – Pablo Pazos Aug 29 '18 at 05:20
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"); 
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
Ankit
  • 6,554
  • 6
  • 49
  • 71
  • It resulted, but it is printing `Wed Aug 01 00:00:00 BST 2012`, even my format is `SimpleDateFormat("yyyy-MM-dd")` – user2144555 Apr 02 '13 at 10:12