简体   繁体   中英

How to split date and time from a datetime string?

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?

(Edit: See Answer by Ole VV 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));

java.time, the modern Java date and time API, and ThreeTenABP

It's time someone provides the modern answer to this question. I do here.

I am not at complete ease with your requirements, though. For the vast majority of purposes and situations you should not keep your date nor your time of day in a string. You should use proper date-time objects. So as I see it, this is what you should want to do:

    LocalDateTime dateTime = LocalDateTime.of(2011, Month.AUGUST, 29, 11, 16, 12);
    LocalDate date = dateTime.toLocalDate();
    LocalTime time = dateTime.toLocalTime();
    System.out.println("date = " + date);
    System.out.println("time = " + time);

Output is:

 date = 2011-08-29 time = 11:16:12

Assuming that 8/29/2011 11:16:12 AM has been entered as user input you need to parse it into a LocalDateTime that you can keep in your program. This goes like this:

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("M/d/u h:m:s a", Locale.ENGLISH);
    String userInput = "8/29/2011 11:16:12 AM";
    LocalDateTime dateTime = LocalDateTime.parse(userInput, formatter);
    System.out.println("dateTime = " + dateTime);
 dateTime = 2011-08-29T11:16:12

Going the other way, to output to the user: If your separate date and time strings are for output only, we don't need to separate date and time before formatting into those strings. We can format the LocalDateTime directly.

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("M/d/u");
    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofPattern("h:mm:ss a", Locale.ENGLISH);
    String dateString = dateTime.format(dateFormatter);
    String timeString = dateTime.format(timeFormatter);
    System.out.println("dateString = " + dateString);
    System.out.println("timeString = " + timeString);
 dateString = 8/29/2011 timeString = 11:16:12 AM

Question: Doesn't java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6 .

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It's called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Why not to use DateFormat?

Check http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html

String str = "8/29/2011 11:16:12 AM";

String fmt = "MM/dd/yyyy HH:mm:ss a";
DateFormat df = new SimpleDateFormat(fmt);

Date dt = df.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);

It gives more work/code but it's the proper way to do it.

Try this:

String main = "8/29/2011 11:16:12 AM";
        String[] tmp;
        String date, time;

        tmp = main.split(" ");

        // [0] = 8/29/2011
        // [1] = 11:16:12
        // [2] = AM

        date = tmp[0].toString(); // 8/29/2011
        time = tmp[1].toString() + " " + tmp[2].toString(); // 11:16:12 AM

Try the split function in Java:

String my_string="8/29/2011 11:16:12 AM"
String [] my_date_time = null;
my_date_time = my_string.split(" ");
String Date_str=my_date_time[0];
String Time_str=my_date_time[1]+" "+my_date_time[2];

You get variable Strings like this Date_str="8/29/2011" and Time_str="11:16:12 AM"

String str = "8/29/2011 11:16:12 AM"
String date = str.subString(0, str.indexOf(' '));
String time  = str.subString(str.indexOf(' ')+1);
mDate = new Date();
DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
DateFormat dateFormat = SimpleDateFormat.getDateInstance();
timeFormat.format(mDate); // formats to: 4:53:03 AM
dateFormat.format(mDate); // formats to: Oct 16, 2014

You can do it by splitting your string into two substrings, as follows

String main = "8/29/2011 11:16:12 AM";
String s[] = main.split(" ",2);
String date = s[0];
String time = s[1];

NOTE : The split method will split the string into two parts as mentioned in the second argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM