0

I need help to format the date in the code that is below. Should be the date shown on the form: 05. May 2014. Please give me suggestions how to do it.

package person;
public class Person {

public static void main(String[] split) {

    String text = "John.Davidson/05051988/Belgrade Michael.Barton/01011968/Krakov Ivan.Perkinson/23051986/Moscow";
    String[] newText = text.split("[./ ]");
    for(int i=0; i<newText.length; i+=4)
    {
         String name = newText[i].split(" ")[0];
         String lastName = newText[i+1].split(" ")[0];
         String dateOfBirth = newText[i+2].split(" ")[0];
         String placeOfBirth = newText[i+3].split(" ")[0];

         System.out.println("Name: " + name + ", last name: " + lastName + ", date of birth: " + dateOfBirth + ", place of birth: " + placeOfBirth);
    }
}

}
ArnonZ
  • 3,822
  • 4
  • 32
  • 42
rapi
  • 23
  • 3

4 Answers4

1

Try this way

String dateOfBirth = newText[i+2].split(" ")[0];
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.ENGLISH);
Date date = dateFormat.parse(dateOfBirth);
SimpleDateFormat dF = new SimpleDateFormat("dd. MMMM yyyy", Locale.ENGLISH);
System.out.println(dF.format(date));

Dont forget to handle the exception

SparkOn
  • 8,806
  • 4
  • 29
  • 34
1

Suggestion : use the utility class in the SDK :

Pierre Rust
  • 2,474
  • 18
  • 15
0
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Format {


    public static void main(String[] args) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("dd ',' MMM yyyy", Locale.ENGLISH);
        SimpleDateFormat parser = new SimpleDateFormat("ddMMyyyy");
        String text = "John.Davidson/05051988/Belgrade Michael.Barton/01011968/Krakov Ivan.Perkinson/23051986/Moscow";
        String[] newText = text.split("[./ ]");
        for(int i=0; i<newText.length; i+=4)
        {
            String name = newText[i].split(" ")[0];
            String lastName = newText[i+1].split(" ")[0];
            String dateOfBirth = newText[i+2].split(" ")[0];
            String placeOfBirth = newText[i+3].split(" ")[0];


            System.out.println("Name: " + name + ", last name: " + lastName + ", date of birth: " + formatter.format(parser.parse(dateOfBirth)) + ", place of birth: " + placeOfBirth);
        }}


}
sol4me
  • 15,233
  • 5
  • 34
  • 34
0

You can do it like this.

Keep in mind that SimpleDateFormat is NOT THREAD SAFE.

"Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."

    SimpleDateFormat FromDate = new SimpleDateFormat("mmDDyyyy");
    Date date = FromDate.parse("05051988");
    SimpleDateFormat toFormat = new SimpleDateFormat("dd. MMMM yyyy");
    String result = toFormat.format(date);
folkol
  • 4,752
  • 22
  • 25