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?
One of the best ways to Separate a date from a date and time value is by using the INT function. INT function takes an integer from a number and left out the fractional part.
parse(str); DateFormat tdf = new SimpleDateFormat("HH:mm:ss a"); DateFormat dfmt = new SimpleDateFormat("MM/dd/yyyy"); String timeOnly = tdf. format(dt); String dateOnly = dfmt. format(dt);
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();
}
}
}
Try this:
String date = "12/8/2012";
String time = "11:25 am";
String[] date1 = date.split("/");
String[] time1 = time.split(":");
String[] time2 = time1[1].split(" "); // to remove am/pm
Calendar beginTime = Calendar.getInstance();
beginTime.set(Integer.parseInt(date1[2]), Integer.parseInt(date1[1]), Integer.parseInt(date1[0]), Integer.parseInt(time1[0]), Integer.parseInt(time2[0]));
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);
Hope this helps.
Assuming you get your date in String format (if not, convert it!) and then this:
String date = "12/8/2012";
String[] dateParts = date.split("/");
String day = dateParts[0];
String month = dateParts[1];
Similarly u can split time as well!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With