JavaDevNotes.com

Java String To Date

String is an all around data structure for saving information because it can handle arbitrary sequence of characters. Often times, it is also used to store numeric, date, or other type of information. Sometimes we need to convert a String object to another data structure. For example, if an HTML form submits a date information to the server, each data in the form are passed as String. In this case, we would need to convert the String to Date such that other computations can be performed. For example, determining the age based on birth date and current date. Below are some ways on how we could convert a String into Date for some specific condition or method.

Convert String to Date using SimpleDateFormat

SimpleDateFormat is the easiest utility we could use to convert a String to Date and vice versa. It is powerful and flexible that we don't need to write our own implementation. It covers many scenarios that is sufficient for most of what we would need.
  • Convert Simple Date
    Here is a simple example that will parse a String with date only information in numeric representation separated by backslash.
    package mytest;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class Test {
        public static void main(String[] args) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date dt = sdf.parse("28/10/1965");
            System.out.println(dt);
        }
    }
    
    The SimpleDateFormat is created passing the pattern of the date format it expects. Then it's parse method can be used to parse a String object that follows the convention. The above code will output:
    Thu Oct 28 00:00:00 PDT 1965
    
    Once created, we can reuse the same SimpleDateFormat to parse multiple String instances:
    package mytest;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class Test {
        public static void main(String[] args) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date dt1 = sdf.parse("28/10/1965");
            Date dt2 = sdf.parse("15/11/1931");
            Date dt3 = sdf.parse("25/12/1989");
            System.out.println(dt1);
            System.out.println(dt2);
            System.out.println(dt3);
        }
    }
    
    The code will successfully parse the three date strings and the output will be:
    Thu Oct 28 00:00:00 PDT 1965
    Sun Nov 15 00:00:00 PDT 1931
    Mon Dec 25 00:00:00 PDT 1989
    
    Make sure that the String given to be parse will follow the declared format. For example:
    package mytest;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class Test {
        public static void main(String[] args) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date dt = sdf.parse("28-10-1965");
            System.out.println(dt);
        }
    }
    
    Will throw an exception:
    Exception in thread "main" java.text.ParseException: Unparseable date: "28-10-1965"
    	at java.text.DateFormat.parse(DateFormat.java:366)
    	at mytest.Test.main(Test.java:8)
    
  • Convert Date With Time Component
    SimepleDateFormat can also convert String with time component to Date. For example:
    package mytest;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class Test {
        public static void main(String[] args) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            Date dt = sdf.parse("28/10/1965 12:30:15");
            System.out.println(dt);
        }
    }
    
    The format "HH:mm:ss" means hour, minutes, and seconds. And it will parse our String accordingly and display the following output:
    Thu Oct 28 12:30:15 PDT 1965
    
  • Convert Date With Name of Month
    SimpleDateFormat can also parse Strings where month is represented by it's logical name and not by number only. For example:
    package mytest;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class Test {
        public static void main(String[] args) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy");
            Date dt = sdf.parse("November 11, 2018");
            System.out.println(dt);
        }
    }
    
    The format "MMMM" means the full name of the month. Thus the code above will output:
    Sun Nov 11 00:00:00 PDT 2018
    
The following are the letters we can use for creating SimpleDateFormat with definition and example.


Letter    Date or Time Component     Presentation    Examples
GEra designatorTextAD
yYearYear1996; 96
YWeek yearYear2009; 09
MMonth in year (context sensitive)MonthJuly; Jul; 07
LMonth in year (standalone form)MonthJuly; Jul; 07
wWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
dDay in monthNumber10
FDay of week in monthNumber2
EDay name in weekTextTuesday; Tue
uDay number of week (1 = Monday, ..., 7 = Sunday)Number1
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard Time; PST; GMT-08:00
ZTime zoneRFC 822 time zone-0800
XTime zoneISO 8601 time zone-08; -0800; -08:00

Caveat
Once caveat when working with SimpleDateFormat is that it is not a thread safe object. Meaning if multiple threads are using the same instance to parse a String to date, it may produce unexpected results.

Convert String to Date using Joda-Time Library

Another way to convert String to Date object is to use the Joda-Time library. Many Java developers prefer to use Joda prior to Java 1.8 because of it's power and ease of use. Here is a simple example:
package mytest;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Test {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
        String dateInString = "28/10/2018";
        DateTime dateTime = DateTime.parse(dateInString, formatter);
        Date date = dateTime.toDate();
        System.out.println(date);
    }
}
Which will output:
Sun Oct 28 00:00:00 PDT 2018
And below is using name of Month with time component:
package mytest;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Test {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM dd, yyyy HH:mm:ss");
        String dateInString = "November 11, 2018 12:30:59";
        DateTime dateTime = DateTime.parse(dateInString, formatter);
        Date date = dateTime.toDate();
        System.out.println(date);
    }
}
Which will output:
Sun Nov 11 12:30:59 PDT 2018

Convert String to Date using Apache's DateUtils

As always, many Java developers love the utilities from Apache projects. For this particular purpose, we can use the DateUtils from Apache Commons Lang. Here is a simple example:

package mytest;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public class Test {
    public static void main(String[] args) throws ParseException {
        String stringDate = "28/10/2018";
        Date date = DateUtils.parseDate(stringDate, "dd/MM/yyyy");
        System.out.println(date);
    }
}
Which is very similar to the methods we tried above. The output is expected to be:
Sun Oct 28 00:00:00 PDT 2018
And another example with name of month and time component:
package mytest;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public class Test {
    public static void main(String[] args) throws ParseException {
        String stringDate = "November 11, 2018 12:30:59";
        Date date = DateUtils.parseDate(stringDate, "MMMM dd, yyyy HH:mm:ss");
        System.out.println(date);
    }
}
Which will of course display the output:
Sun Nov 11 12:30:59 PHT 2018

Convert String to Date using Java 8 DateTimeFormatter

If we are on Java 8 and above, we can use DateTimeFormatter to convert a String to a LocalDate, and then LocalDate to a Date object. Here is an example:
package mytest;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class Test {
    public static void main(String[] args) {
        String stringDate = "28/10/2018";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        LocalDate localDate = LocalDate.parse(stringDate, formatter);
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        System.out.println(date);
    }
}
The output is the same as all our examples above:
Sun Oct 28 00:00:00 PDT 2018

Support my blog by buying some of my t-shirt, mug, and phone case designs!
                   

String Tutorials And Examples