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
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
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).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.