How to convert date string to date
How to convert date string to date
How to convert a string to date in Java
December 22, 2019 • Atta ✨
String to date conversion is one of the most frequent tasks in Java or any other programming language. It is useful to know how to perform string to date conversion before working on Java projects.
In this tutorial, you’ll learn about different ways to convert a string object to a date object in Java. We’ll first look at utility methods provided by Java 8 new date and time API to perform string to date conversion. Afterward, we’ll also look at the legacy java.util.Date class that is also used to represent dates. Finally, we’ll discuss 3rd-party libraries like Apache Commons Lang that can also be used to perform this conversion.
Java 8 Date & Time API
Java 8 introduced a new date and time API (classes in java.time.* package) to make it easier to work with dates in Java. By default, these classes use ISO-8601 format to represent dates and times.
parse() Method
The new API provides the parse() method that accepts a sequence of characters as an argument and uses the ISO_LOCAL_DATE format to parse the string into a date:
To convert a string into an instance of date using the above method, the string must be in ISO-8601 format. Otherwise, a DateTimeParseException will be thrown at runtime.
Alternatively, you can pass another parameter to parse() to explicitly define the string pattern:
A DateTimeFormatter instance is used as a formatter for formatting and parsing date-time objects in Java 8 new date and time API.
Convert String to LocalDate
The above code is equivalent of writing the following code to instantiate a LocalDate instance:
If the string is not in ISO-8601 format, you must define a custom formatter using DateTimeFormatter as shown below:
Here is another example that uses the pre-defined formatter BASIC_ISO_DATE from DateTimeFormatter to parse a string into a LocalDate :
Convert String to LocalTime
The above code is equivalent of writing the following code to instantiate an instance of LocalTime :
For non ISO-8601 string formats, you have to pass a formatter using DateTimeFormatter as shown below:
Convert String to LocalDateTime
The LocalDateTime class is the most popular class for handling date and time together in Java 8 and higher. It stores a combination of date and time without timezone in ISO-8601 format (yyyy-MM-ddTHH:mm).
The above code is equivalent to the following code that instantiates an instance of LocalDateTime :
To convert a string with a custom date format into a LocalDateTime object, you need to supply a formatter using DateTimeFormatter :
Convert String to ZonedDateTime
The ZonedDateTime class is used to deal with timezone specific dates and times. It represents a date-time with a timezone in the ISO-8601 format (e.g. 2010-05-15T10:15:30+01:00[Europe/Paris]).
Convert String to OffsetDateTime
The OffsetDateTime class represents a date and time with an offset from UTC/Greenwich in the ISO-8601 format (e.g. 1992-06-30T23:15:30-03:30).
The following example demonstrates how you can convert an ISO-8601 string into an instance of OffsetDateTime :
Convert String to Instant
The Instant class represents a specific moment on the timeline. To convert a string into an Instant object, the string must be in ISO_INSTANT format (e.g. 2011-12-03T10:15:30Z).
Here is an example:
You can easily convert an Instant object to any other date-time format like LocalDateTime or ZonedDateTime :
Here is the output of the above code snippet:
Convert String to java.util.Date
Before Java 8, both java.util.Date and java.util.Calendar classes were used to handle dates and times. These classes are not actively used today but they are still worth covering as most of the legacy codes are still using them.
The above code generates the following output:
However, you can format the Date object and add the timezone information to a string using SimpleDateFormat :
Here is the output of the above code:
DateTimeFormatter vs SimpleDateFormat
The DateTimeFormatter class is thread-safe unlike its older counterpart and offers new utility methods and constants for various date and time formats.
Let us look at the below example:
As you can see above, the difference between DateTimeFormatter and SimpleDateFormat is very much clear. In the new date and time API, the classes have their own parse and format methods and use DateTimeFormatter for the sake of defining patterns only. In the older API, a formatter is used to both parse and format the date.
Rule of thumb, use DateTimeFormatter if you are using Java 8 new date and time API. For legacy codebase (Java 7 and below), use SimpleDateFormat for patterns.
3rd-Party Libraries
Now that we have developed a good understanding of performing string to date conversion using both new and old APIs included in core Java, let us look at some external libraries.
Joda-Time
Before Java 8, Joda-Time was developed to overcome the shortcomings of old date and time API. It provided an excellent alternative to core Java date and time classes and quickly became a de facto standard date and time library for Java before Java SE 8.
As of Java 8, all of its functionality is already implemented in the core Java in the form of the new date and time API. That is why the author of Joda-Time recommends users to migrate to Java 8 java.time (JSR-310) for working with dates and times.
In case if the migration is not possible, or if you are still using Java 7 or below, Joda-Time is still a great library to use.
To add Joda-Time to your Maven project, add the following dependency to pom.xml file:
For a Gradle project, include the below dependency to your build.gralde file:
Working with Joda-Time is very much similar to working with Java 8 new date and time API. Here is a quick example:
The DateTime class from Joda-Time also supports the timezone information:
Apache Commons Lang
The Apache Commons Lang library is another important 3rd-party library that provides many useful utility classes for working with legacy Date and Calendar classes.
To add the library to your Maven project, add the following dependency to pom.xml file:
For Gradle, add the below dependency to your build.gradle file:
Now you can use the DateUtils class from Apache Commons Lang to parse a string into a Date object:
As you can see above, DateUtils.parseDate() accepts an array of patterns. It will parse each pattern after another. If no pattern matches the given input string, it throws a ParseException exception.
Common Date and Time Patterns
Let us take a look at some of the most common patterns that you can use with DateTimeFormatter and SimpleDateFormat for formatting and parsing dates and times:
Look at this JavaDoc for a full list of symbols that you can use to define a date and time pattern for parsing a string into a date.
Summary
String to date conversion is one of the most frequent operations in Java. In this article, we have covered multiple ways to convert a string object into a date object including Java 8 new date and time API, legacy Date class, 3rd-party libraries like Joda-Time and Apache Commons Lang.
The new date and time API provides an extensive set of classes for parsing different types of strings into the newest API date and time objects. These classes are thread-safe, backward-compatible, and easier-to-use. You should always use the new API for parsing and formatting dates and times in Java 8 and higher.
If, for some reason, you cannot use the new API, go for the Joda-Time library. It is an excellent replacement of core Java date and time API before Java 8.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
Parsing strings to convert them to DateTime objects requires you to specify information about how the dates and times are represented as text. Different cultures use different orders for day, month, and year. Some time representations use a 24-hour clock, others specify «AM» and «PM.» Some applications need only the date. Others need only the time. Still others need to specify both the date and the time. The methods that convert strings to DateTime objects enable you to provide detailed information about the formats you expect and the elements of a date and time your application needs. There are three subtasks to correctly converting text into a DateTime:
The Parse and TryParse methods convert many common representations of a date and time. The ParseExact and TryParseExact methods convert a string representation that conforms to the pattern specified by a date and time format string. (See the articles on standard date and time format strings and custom date and time format strings for details.)
The current DateTimeFormatInfo object provides more control over how text should be interpreted as a date and time. Properties of a DateTimeFormatInfo describe the date and time separators, the names of months, days, and eras, and the format for the «AM» and «PM» designations. The CultureInfo returned by CultureInfo.CurrentCulture has a CultureInfo.DateTimeFormat property that represents the current culture. If you want a specific culture or custom settings, you specify the IFormatProvider parameter of a parsing method. For the IFormatProvider parameter, specify a CultureInfo object, which represents a culture, or a DateTimeFormatInfo object.
The text representing a date or time may be missing some information. For example, most people would assume the date «March 12» represents the current year. Similarly, «March 2018» represents the month of March in the year 2018. Text representing time often does only includes hours, minutes, and an AM/PM designation. Parsing methods handle this missing information by using reasonable defaults:
If the date is present in the string, it must include the month and one of the day or year. If the time is present, it must include the hour, and either the minutes or the AM/PM designator.
The format provider is also used to interpret an ambiguous numeric date. It is not clear which components of the date represented by the string «02/03/04» are the month, day, and year. The components are interpreted according to the order of similar date formats in the format provider.
Parse
The following example illustrates the use of the DateTime.Parse method to convert a string into a DateTime. This example uses the culture associated with the current thread. If the CultureInfo associated with the current culture cannot parse the input string, a FormatException is thrown.
All the C# samples in this article run in your browser. Press the Run button to see the output. You can also edit them to experiment yourself.
These examples are available in the GitHub docs repo for both C# and Visual Basic.
You can also explicitly define the culture whose formatting conventions are used when you parse a string. You specify one of the standard DateTimeFormatInfo objects returned by the CultureInfo.DateTimeFormat property. The following example uses a format provider to parse a German string into a DateTime. It creates a CultureInfo representing the de-DE culture. That CultureInfo object ensures successful parsing of this particular string. This precludes whatever setting is in the CurrentCulture of the CurrentThread.
However, although you can use overloads of the Parse method to specify custom format providers, the method does not support parsing non-standard formats. To parse a date and time expressed in a non-standard format, use the ParseExact method instead.
The following example uses the DateTimeStyles enumeration to specify that the current date and time information should not be added to the DateTime for unspecified fields.