Search code examples
javajava-8java-timejava-6date-parsing

Java 6 alternatives for LocalDate and DateTimeFormatter


In a Java 8 project, I can parse the date this way:

LocalDate.parse(
    newDateString, 
    DateTimeFormatter.ofPattern(expectedDateFormat) 
)
.format(
    DateTimeFormatter.ofPattern(expectedDBDateFormat)
);

My problem is that I have a Java 6 project, and LocalDate and DateTimeFormatter are not defined for Java 6.

How can I parse the date in my Java 6 project?


Solution

  • I would like to use Joda time, you can just make some changes in your code, your code should like like this :

    LocalDate.parse(
         newDateString, DateTimeFormat.forPattern(expectedDateFormat)
    ).toString(DateTimeFormat.forPattern(expectedDBDateFormat));
    

    The imports

    The imports should be :

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

    Instead of :

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    

    Method names

    If you note there are a small changes :

    In Java 8 Time                            In Joda Time 
    ofPattern(String pattern)           =>    forPattern(String pattern)   
    format(DateTimeFormatter format)    =>    toString(DateTimeFormat format)