Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 568
Louis Evans Avatar asked Aug 07 '13 09:08

Louis Evans


People also ask

How do I separate a date and time in a spreadsheet?

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.

How to split timestamp in Java?

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


3 Answers

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();
        }
    }
}
like image 195
Harry.Chen Avatar answered Sep 27 '22 18:09

Harry.Chen


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.

like image 35
MysticMagicϡ Avatar answered Sep 27 '22 19:09

MysticMagicϡ


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!

like image 41
Jazib Avatar answered Sep 27 '22 18:09

Jazib