How To - Convert String to Date



Description:

These are the two main ways to convert a string to a date.

Method 1: Using SimpleDateFormatter

Here is the code for this method:

public class dateTester {
    
    public String myBirthday = "1998/01/30";
    
    public Date convertStringtoDate() {
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date birthDate = format.parse(myBirthday); // Handle the ParseException here
        return birthDate;
    }
    
}

Method 2: Using Substrings

Here is the code for this method:

public class dateTester {
    
    public String myBirthday = "1998/01/30";
    
    public Date convertStringtoDate() {
        String year = myBirthday.substring(0, 4);
        String month = myBirthday.substring(5,7);
        String day = myBirthday.substring(8,10);
        Date birthDate = new Date(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
        return birthDate;
    }   

    
}

java_strings.htm

Advertisements