Split date/time strings

限于喜欢 提交于 2019-12-14 04:16:59

问题


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?


回答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;

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



回答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/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.




回答3:


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!




回答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..




回答5:


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




回答6:


This is just a Idea, you can do some thing like this without splitting

    DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
    Date date = formatter.parse("12/8/2012 11:25 am");      
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);


来源:https://stackoverflow.com/questions/18099285/split-date-time-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!