Skip to content Skip to sidebar Skip to footer

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' &

Solution 1:

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;

publicclassDateTest {

    publicstaticvoidmain(String[] args) {
        Stringdate="12/8/2012";
        Stringtime="11:25 am";
        DateFormatdf=newSimpleDateFormat("MM/dd/yyyy hh:mm a");
        try {
            Datedt= df.parse(date + " " + time);
            Calendarca= Calendar.getInstance();
            ca.setTime(dt);
            System.out.println(ca.getTimeInMillis());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Solution 2:

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/pmCalendar 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.

Solution 3:

Assuming you get your date in String format (if not, convert it!) and then this:

Stringdate = "12/8/2012";
String[] dateParts = date.split("/");
String day = dateParts[0]; 
String month = dateParts[1]; 

Similarly u can split time as well!

Solution 4:

You can see an example of split method here : How to split a string in Java

Then simply use the array for your parameter eg: array[0] for year and etc..

Solution 5:

Use SimpleDateFormat (check api docs). If you provide proper time pattern it will be able to convert string into Date instantly.

Post a Comment for "Split Date/time Strings"