Android how to convert this format(/Date(1418346257000+0700)/) to Date object

701 views Asked by At

The web service returns me the format like this /Date(1418346257000+0700)/. How can I convert it to Date object.

1

There are 1 answers

1
Silambarasan Poonguti On

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();
}