MySQL “/Date(…)/” object in JSON string in Android project
Question: In Android Java project I have to call a Microsoft .NET web service using soap. The response is a complex data structure in JSON string including a mySQL DateTime object in a strange format, like: “/Date(126521670000-0700)/”. How can I convert it into java.util.Date object or human readable text format in Android?
Answer: You received the date in a known format and should extract the parts of date and time zone first. In the next step convert them into java objects. The date is in milliseconds since January 1, 1970 00:00:00 UTC. Example code is here:
Log.i("WS Test", "Received=" + dateStringFromJSON );
// Remove prefix and suffix extra string information
String dateString = dateStringFromJSON.replace("/Date(", "").replace(")/", "");
// Split date and timezone parts
String[] dateParts = dateString.split("[+-]");
// The date must be in milliseconds since January 1, 1970 00:00:00 UTC
// We want to be sure that it is a valid date and time, aka the use of Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(dateParts[0]));
// If you want to play with time zone:
calendar.setTimeZone(TimeZone.getTimeZone(dateParts[1]));
// Read back and look at it, it must be the same
long timeinmilliseconds = calendar.getTimeInMillis();
// Convert it to a Date() object now:
Date date = calendar.getTime();
// Convert it to a formatted string as you wish:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
// Show it in the Log window:
Log.i("WS Test", "Received date and time=" + formatter.format(date) );