How to parse String to Date in Java using JodaTime Example

In this Java tutorial, we will learn how to parse String to Date using Joda-Time library, for example, we will convert date String "04-12-2014" to java.util.Date object which represents this date. Before Java 8 introduced its new Date and Time API,  Joda was only reliable, safe and easy way to deal with date and time intricacies in Java. Java's own Date and Time was not that great, starting from JDK 1.1 when they made java.util.Date a mutable object and when they introduced Calendar in Java 1.2. It is one of the most criticized feature of Java on communities along with checked exception and object cloning. Even though Java 8 has corrected its mistake with an excellent, shiny new API, which addresses all past issue, Joda date and time library still has a role to play in Java systems. First and foremost reason is because most of the large banks and clients are still running on Java 1.6 and will likely take another 5 to 6 year to adopt Java 8, Joda is the only friend you can trust to deal with date and time nightmares.

One of the most common task in Java is to parse String to Dates and even though Java provides a utility class called SimpleDateFormat, its not safe to use in multi-threaded environment until you know how to use thread confinement to make SimpleDateFormat thread-safe.

Many beginners either create new instance of SimpleDateFormat each time they have to convert String to Date or commit classical mistake of storing it in an instance or static variable, only to face mysterious issues later. Since most of the Joda Time classes are Immutable, you can use them easily and safely in concurrent application.

Btw, if you are running on Java SE 8 then you should use new Date and Time API as it's going to be the standard in coming years and it will also remove the dependency on a third party library. You can also take help of Java SE 8 for Really Impatient by Cay S. Horstmann to learn more about this new library, it's quite similar to Joda time.




How to use Joda-Time in Java - JAR and dependency

In order to use Joda-Time library in your Java program, you need to first download the JAR file from http://www.joda.org/joda-time/, or alternatively if you are using Maven then you can also add following dependency in your pom.xml and it will take care of downloading and managing dependencies for you.

<dependency>
  <groupId>joda-time</groupId>
  <artifactId>joda-time</artifactId>
  <version>2.5</version>
</dependency>

If you are not using Maven then just add joda-time-2.5.jar in your Java program's classpath by using either CLASSPATH environment variable or  -classpath option of java command.

Its very important to keep the JAR file at both compile time and runtime to avoid nasty ClassNotFoundException and NoClassDefFoundError. Once you done that, your IDE will guide you while using Joda-Time library. You can see on the spot Java documentation to decide which method to use and why.

As I said earlier, if you are running on JDK 8, you should prefer new Date and Time API of Java 8 instead of using Joda date and time API. It's better to stick with standard JDK classes and API if possible. To learn more about this excellent date and time API, I suggest reading Java SE 8 for Really Impatient by Cay S. Horstmann, one of the better books to learn new features of Java 8.

parse String to Date in Java


Parsing String to Date in Java using Joda Time

Here is my sample Java program, which converts String dates into util date in Java. It's little bit similar to my earlier program, how to convert String to Date in Multithreaded Java program, which was using SimpleDateFormat for parsing, but here we are using Joda-Time DateTimeFormat and DateTimeFormatter classes.  Here are the steps to parse String to Date using Joda library :
  1. Create a date pattern using forPattern() method of DateTimeFormat class.
  2. forPattern() method returns an object of DateTimeFormatter which does actual parsing.
  3. Use parseMillis() method of DateTimeFormatter class to convert String to long millisecond
  4. Now we can create a new java.util.Date() object using this millisecond value

You can see its very simple and safe to parse String to Date using Joda-time library. If you want to change the date format e.g. from "dd/MM/yyyy" to "yyyyMMdd" then you need to call the forPattern() again and get a new DateTimeFormatter instance.

import java.text.ParseException;
import java.util.Date;
import java.util.Scanner;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * How to parse String to date in Java using JodaTime library
 *
 * @author WINDOWS 8
 */

public class JodaDateParser{  
 
   
    public static void main(String args[]) throws ParseException{
     
      String pattern = "dd/MM/yyyy";
       
      System.out.printf("Please enter date in %s format %n", pattern);
      Scanner reader = new Scanner(System.in);
      String aDate = reader.nextLine();
     
      DateTimeFormatter df =DateTimeFormat.forPattern("dd/MM/yyyy");
      long millis = df.parseMillis(aDate);
      Date date  = new Date(millis);
     
      System.out.printf("String %s is equal to date %s in Java %n", aDate, date);
     
      // let's do this for another date format e.g. yyyy/MM/dd
      pattern = "yyyy/MM/dd";
     
      System.out.printf("Please enter date in %s format %n", pattern);
      aDate = reader.nextLine();
     
     
      // needs to create another DateTimeFormatter with new pattern
      df =DateTimeFormat.forPattern("yyyy/MM/dd");
      millis = df.parseMillis(aDate);
      date  = new Date(millis);
     
      System.out.printf("String %s is equal to date %s in Java %n", aDate, date);
      reader.close();
    }
   
   
}

Output
Please enter date in dd/MM/yyyy format
04/12/2014
String 04/12/2014 is equal to date Thu Dec 04 00:00:00 GMT+08:00 2014 in Java
Please enter date in yyyy/MM/dd format
2014/12/03
String 2014/12/03 is equal to date Wed Dec 03 00:00:00 GMT+08:00 2014 in Java

You can see that we are successfully able to convert "04/12/2014" into a java.util.Date instance of same value, and we are even to change the date format to accept String as "yyy/MM/dd" and successfully parse it too.


What will happen if String is an invalid Date?

How to parse String to Date in Java using Joda If you try to parse an invalid date String using Joda time, you will definitely get an error something like ParseException of JDK. In fact Joda Time throws IllegalArgumentException like this when you try to parse an invalid date using DateTimeFormatter class : "java.lang.IllegalArgumentException: Invalid format" error in Java. For example in following snippet, our date format is dd/MM/yyyy but we entered date in some other format e.g. yyyy/MM/dd and that's why DateTimeFormatter from Joda is not able to parse it.

Please enter date in dd/MM/yyyy format
2014/11/23
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2014/11/23" is malformed at "14/11/23"
 at org.joda.time.format.DateTimeParserBucket.doParseMillis(DateTimeParserBucket.java:187)
 at org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:780)
 at JodaDateParser.main(JodaDateParser.java:26)

That's all about how to parse String to Date in Java using Joda Date and Time library. If you know this library, it would be pretty easy to learn the new Java date and time library introduced in Java 8. It is actually inspired by JodaTime and continued the tradition of immutable, thread-safe and less confusing date time API.

If you like this tutorial and want to learn more about how to deal with dates and time in Java, you will like these amazing articles too :
  • How to format date in Java? (solution)
  • How to convert java.sql.Date to java.util.Date in Java? (solution)
  • How to convert java.util.Date to java.sql.Date in Java? (solution)
  • How to display date in multiple Timzone in Java? (example)
  • How to get current month, year, day and day of week in Java? (solution)
  • Difference between java.sql.Time, java.sql.Timestamp and java.util.Date in Java? (answer)
  • How to compare two dates in Java? (solution)
  • SimpleDateFormat is not thread-safe, Use it carefully? (answer)
  • How to convert local time to GMT time in Java? (solution)
  • How to add, subtract days, month and year from date in Java? (example)
  • How to convert XMLGregorianCalendar to Date in Java? (solution)
  • How to convert millisecond to Date in Java? (solution)

No comments:

Post a Comment