Tom Finet Tom Finet - 3 months ago 15
Java Question

How to parse date string into integer variables?

I have a

String
which is formatted like so:
"dd-MM-yyyy"
. I am trying to get the
dd
part of the string saved into a integer
day
variable. I want to do the same for the
MM
and
yyyy
parts of the
String
. I can imagine parsing the
String
using a for loop to separate the
String
whenever the
"/" char
is at the current index in the
for
loop.

How do I split the
String
containing the date into day, month and year respectively, into integer variables for me to operate on? Perhaps transferring this
String
to a
Date
object would make it easier due to a member method or field that handles this (just a thought).

Answer
        String date = "13-08-2016";
        String[] values = date.split("-");
        int day = Integer.parseInt(values[0]);
        int month = Integer.parseInt(values[1]);
        int year = Integer.parseInt(values[2]);

You can use String.split(String regex) method to parse the date to array of String then convert each value to int.

JavaDoc:

public String[] split(String regex) Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Read more here: String.split

Comments