Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a string like 8/29/2011 11:16:12 AM. I want to split that string into separate variables like

date = 8/29/2011
time = 11:16:12 AM

Is this possible? If so, how would I do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
121 views
Welcome To Ask or Share your Answers For Others

1 Answer

(Edit: See Answer by Ole V.V. below for a more modern (Java 8) approach for the first version)

One way to do is parse it to a date object and reformat it again:

    try {
        DateFormat f = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
        Date d = f.parse("8/29/2011 11:16:12 AM");
        DateFormat date = new SimpleDateFormat("MM/dd/yyyy");
        DateFormat time = new SimpleDateFormat("hh:mm:ss a");
        System.out.println("Date: " + date.format(d));
        System.out.println("Time: " + time.format(d));
    } catch (ParseException e) {
        e.printStackTrace();
    }

If you just want to slice it into date-time pieces, just use split to get pieces

    String date = "8/29/2011 11:16:12 AM";
    String[] parts = date.split(" ");
    System.out.println("Date: " + parts[0]);
    System.out.println("Time: " + parts[1] + " " + parts[2]);

or

    String date = "8/29/2011 11:16:12 AM";
    System.out.println("Date: " + date.substring(0, date.indexOf(' ')));
    System.out.println("Time: " + date.substring(date.indexOf(' ') + 1));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...