Grails Cookbook - A collection of tutorials and examples

Converting Java String To Date

String is sometimes used in storing data such as date, numeric, alpha numeric, or other type of data. It's become a versatile data structure primarily because it's capable of handling random sequence of characters. That said, a String can be converted into another data structure.


Let's say an html form wants to render a date which is in String data structure, to the server for a required information. Now in order to be available for other computations, the string should be converted. In this post, our main example should revolve in determining age with a given current date and birth date.

Observe and study the process on converting a String to Date in order to satisfy certain methods and conditions.

Sample Of Converting String to Date Using Java 8 DateTimeFormatter

Now when we want to convert String to a LocalDate and then turn ii to a Date object, what we want to consider using is the DateTimeFormatter.
Observe ans study the written sample below for a better understanding:
package sampletest;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class TestDateTimeFormatter {
    public static void main(String[] args) {
        String dateString = "01/05/1989";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        LocalDate localDate = LocalDate.parse(dateString, formatter);
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        System.out.println(date);
    }
}
This displays the same result from the example written above. Only this time, we've utilized the DateTimeFormatter to convert string.
Mon May 01 00:00:00 PDT 1989

Sample Of Converting String to Date Using Joda-Time Library

One convenient way to convert String to Date object is the Joda-Time library. Check out the written sample below on how it works:
package sampletest;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class TestJodaTimeLib {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
        String dateString = "20/03/2019";
        DateTime dateTime = DateTime.parse(dateString, formatter);
        Date date = dateTime.toDate();
        System.out.println(date);
    }
}
This is the result of the code above:
Wed Mar 20 00:00:00 PDT 2019
The same implementation works for the altered version of the code below, only this time, we include the time.
package sampletest;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class TestJodaTimeLib {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM dd, yyyy HH:mm:ss");
        String dateString = "October 21, 2018 10:30:57";
        DateTime dateTime = DateTime.parse(dateString, formatter);
        Date date = dateTime.toDate();
        System.out.println(date);
    }
}
Check out the result below:
Sun October 21 10:30:57 PDT 2018

Converting String To Date Using SimpleDateFormat

One simple and easy method we can utilize is using SimpleDateFormat. Not only this utility is powerful, it's also flexible in converting a String to Date process. That said, it's not necessary to implement what we need to write anymore, SimepleDateFormat is logically adequate for our main requirement.

Sample Of Converting Simple Date

Study and observe the written example below, it will analyze consistently the string with specific date information in numeric presentation. Know this is set apart by backslash.
package sampletest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSimpleDate {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdformat = new SimpleDateFormat("dd/MM/yyyy");
        Date dt = sdformat.parse("27/02/2004");
        System.out.println(dt);
    }
}
The SimpleDateFormat expects the date format as "dd/MM/yyyy", it is then passed with the parse method which can be now utilized to analyze parts by parts a string object that comes after the protocol.

This is the result of the written code above:

Fri Feb 27 00:00:00 PDT 2004

Once we're done with this, we can repeat the same process when we work with multiple string instances:

package sampletest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSimpleDate {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdformat = new SimpleDateFormat("dd/MM/yyyy");
        Date dt1 = sdformat.parse("15/02/1994");
        Date dt2 = sdformat.parse("29/08/1992");
        Date dt3 = sdformat.parse("27/08/1989");
        System.out.println(dt1);
        System.out.println(dt2);
        System.out.println(dt3);
    }
}
The output will succesfully show the three date strings:
Tue Feb 15 00:00:00 PDT 1994
Sat Aug 29 00:00:00 PDT 1992
Sun Aug 27 00:00:00 PDT 1989

Bear in mind that the given date format of the SimpleDateFormat should be the same with the declared date format. Once this is unlikely, Java will warn you with an exception. Check the altered code below:
package sampletest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSimpleDate {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdformat = new SimpleDateFormat("dd/MM/yyyy");
        Date dt = sdformat.parse("27-12-1993");
        System.out.println(dt);
    }
}
Exception in thread "main" java.text.ParseException: Unparseable date: "27-12-1993"
	at java.text.DateFormat.parse(DateFormat.java:366)
	at sampletest.TestSimpleDate.main(TestSimpleDate.java:8)

Sample Of Converting Date With Time Component

Let's include time with date, since SimpleDateFormat can utilize both and is capable in converting time. Understand the written sample below:
package sampletest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSimpleDate {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdformat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        Date dt = sdformat.parse("11/01/1982 11:30:02");
        System.out.println(dt);
    }
}
When we break down the format "HH:mm:ss", "HH" means hour, "mm" is minutes, and we know that "ss" is seconds. SimpleDateFormat can convert String to the time component according to the displayed format.

Check out the result below:


Mon Jan 11 11:30:02 PDT 1982

Sample Of Converting Date With Name of Month

Month can also be catered by SimepleDateFormat, in which it can parse Strings with the month's logical name.
See the example below:
package sampletest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestNameMonth {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdformat = new SimpleDateFormat("MMMM dd, yyyy");
        Date dt = sdformat.parse("December 12, 2019");
        System.out.println(dt);
    }
}
Since we've used the String "MMMM", note that the full name of the month will be shown in the expected result.
Thur December 12 00:00:00 PDT 2019
A little reminder is that when using SimepleDateFormat, be careful with multiple threads that are similar instance. When we convert this string to date, or try to parse the instance - it will result to unexpected outputs.

Sample Of Converting String to Date Using Apache's DateUtils

One way we can convert String to Date is using DateUtils from the Apache Commons Language. Check out the written example on how to do this:
package sampletest;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public class TestJodaTimeLib {
    public static void main(String[] args) throws ParseException {
        String dateString = "17/08/2017";
        Date date = DateUtils.parseDate(dateString, "dd/MM/yyyy");
        System.out.println(date);
    }
}
The code above has the same implementation with the samples we've tried above. See the result below:
Thur Aug 17 00:00:00 PDT 2017
This is another sample including the Month's name together with the time component.
package sampletest;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public class TestJodaTimeLib {
    public static void main(String[] args) throws ParseException {
        String dateString = "November 12, 2018 01:20:59";
        Date date = DateUtils.parseDate(dateString, "MMMM dd, yyyy HH:mm:ss");
        System.out.println(date);
    }
}
The output shows the name of the month and the time frame.
Mon November 12 01:20:59 PHT 2018