Search code examples
androidweb-servicesdatetimeksoap2

Get datetime from WebService to Android Application using Ksoap2 library


I have create a Web Service which returns an array of elements like these:

<Service>
    <id>string</id>
    <description>string</description>
    <last_change_date>dateTime</last_change_date>
</Service>

I am consuming this Web Service from Android device, and I'm using Ksoap2 package. When I receive SoapObject from Web Service using the method:

SoapObject response = (SoapObject)envelope.getResponse();

I usually get the content of response using this code:

String str = (String)response.getProperty(index).toString();

And this, normally works good!
But, for getting last_change_date (type dateTime retrieves from datetime field in a db on SQL Server) I can't use the same method.

So, I'm looking for a mechanism for convert dateTime in any date format (Date or Calendar) in Android.


Solution

  • Yes, you can still get the value of the parameter with that method. What you then have to do is parse the string into a Date object.

    E.g. define the format with:

    private static final SimpleDateFormat httpHeaderDateFormatter =
        new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z", Locale.US);
    

    And implement a parsing method like this:

    private Date parseLastModified(String lastModified) {
        Date date = null;
        if (lastModified != null && lastModified.length() > 0) {
            try {
                date = httpHeaderDateFormatter.parse(lastModified);
            } catch (ParseException e) {
                // otherwise we just leave it empty
            }
        }
        return date;
    }
    

    Of course you have to adapt it to whatever format you get from the server and whatever logic you want to have e.g. when there is no value..