Louis Evans Louis Evans - 4 months ago 30
Android Question

Split date/time strings

I have a ReST service which downloads information about events in a persons calendar...

When it returns the date and time, it returns them as a string

e.g. date = "12/8/2012" & time = "11:25 am"

To put this into the android calendar, I need to do the following:

Calendar beginTime = Calendar.getInstance();
beginTime.set(year, month, day, hour, min);
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);


How can I split the date and time variables so that they are useable in the "beginTime.set() " method?

Answer

I don't thinks you really need how to split the string, in your case it should be 'how to get time in milliseconds from date string', here is an example:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        String date = "12/8/2012";
        String time = "11:25 am";
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
        try {
            Date dt = df.parse(date + " " + time);
            Calendar ca = Calendar.getInstance();
            ca.setTime(dt);
            System.out.println(ca.getTimeInMillis());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
Comments