I need a way to take specific "random" numbers from a string and put them each in separate int variables.
For example this string cannot/shouldnt be changed:
String date = "59598 22-01-19 22:46:32 00 0 0 66.2 UTC(NIST) * ";
I need these three numbers in separet ints "22-01-19". So one int would be called "day" and it holds the number 19, another int is called "month" and it holds the number 1, another int called "year" and it holds the number 22.
This is what it would look like:
String date = "59598 22-01-19 22:46:32 00 0 0 66.2 UTC(NIST) * ";
int day = 0;
int month = 0;
int year = 0;
//(method for finding these numbers and putting them into the separate int variables)
System.out.println(year " " month " " day);
Thank you in advance!
Note: I did not find a solution that explained this well enough for me to understand it, I apologize if there already excists a duplicate of this question.
CodePudding user response:
You could split date twice to get a list of the date
String date = "59598 22-01-19 22:46:32 00 0 0 66.2 UTC(NIST) * ";
String[] splittedDate = date.split(" ")[1].split("-");
int day = Integer.valueOf(splittedDate[2]);
int month = Integer.valueOf(splittedDate[1]);
int year = Integer.valueOf(splittedDate[0]);
//(method for finding these numbers and putting them into the separate int variables)
System.out.println(year " " month " " day);
CodePudding user response:
You need to extract the date (those specific values) from the String. You could use regular expressions (regex) to extract this. Have a look at this solution which is similar to what you want to achieve https://stackoverflow.com/a/33924024/6099890
CodePudding user response:
Presuming that the date is always the second token, you can do it like so.
- split the string on spaces, and use the second token
- define a formatter to parse the date assigning to a
LocalDateinstance. - then pull extract the values
- you can use those extractions to re-format the date
- or you can use the formatter
String date = "59598 22-01-19 22:46:32 00 0 0 66.2 UTC(NIST) * ";
String[] tokens = date.split("\\s ", 3);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(("dd-MM-y"));
LocalDate ld = LocalDate.parse(tokens[1], dtf);
int day = ld.getDayOfMonth();
int year = ld.getYear();
int month = ld.getMonthValue();
System.out.printf("d-d-d%n", day, month, year);
System.out.println(ld.format(dtf));
prints
22-01-19
22-01-19
For more info, check out the java.time package. If you are going to be parsing or manipulating date/time objects, this is an essential class to know.
