The web service returns me the format like this /Date(1418346257000+0700)/. How can I convert it to Date object.
Asked
Active
Viewed 683 times
1 Answers
1
Try this...
public static Date setDate(String date) {
String results = date.replaceAll("^/Date\\(", "");
String millisecond = results.substring(0, results.indexOf('+'));
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(millisecond));
String timezone = results.substring(results.indexOf('+'), results.indexOf(')'));
int hours = Integer.parseInt(timezone.substring(1, 3));
int minutes = Integer.parseInt(timezone.substring(3));
if (timezone.charAt(0) == '+') {
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + hours);
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + minutes);
} else {
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hours);
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) - minutes);
}
return new Date(calendar.getTimeInMillis());
}
Method usage:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String date = setDate("/Date(928129800000+0530)/");
Toast.makeText(MainActivity.this, "DATE: " + date, Toast.LENGTH_SHORT)
.show();
}

Nimantha
- 6,405
- 6
- 28
- 69

Silambarasan Poonguti
- 9,386
- 4
- 45
- 38
-
you have only converted millisecond part , where you should also use time zone for calculating time – Raghav Satyadev May 11 '16 at 09:49