Search code examples
javadate-formatsimpledateformat

Not able to convert string dd/MM/yyyy to Date dd/MM/yyyy in java


I have an input string of the format dd/MM/yyyy, I need to convert it into date dd/MM/yyyy.

My approach is:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String date = formatter.format(formatter.parse("22/09/2016"));
Date convertedDate = formatter.parse(date);

I was expecting 22/09/2016 as a date object, however the format returned was not as expected. O/P=>Mon Sep 12 00:00:00 IST 2016

Any idea where I am going wrong? Thanks in advance!


Solution

  • tl;dr

    LocalDate.parse( "22/09/2016" , DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )
             .format( DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )
    

    Problems

    • You are conflating date-time objects with strings representing date-time values. A date-time object can parse a string, and can generate a string, but the date-time object is always separate and distinct from the string. The string has a format; the date-time object does not.
    • You are using troublesome old date-time classes now supplanted by the java.time classes.
    • You are trying to fit a date-only value into a date-time object (square peg, round hole).
    • You are being tricked by the poorly-designed toString method that silently applies a time zone to an internal value that has no time zone (is UTC).

    Be sure to read the correct Answer by Jon Skeet.

    java.time

    Using the new java.time classes, specifically LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
    LocalDate ld = LocalDate.parse( "22/09/2016" , f );
    

    Generate a String to represent that value in standard ISO 8601 format by calling toString.

    String output = ld.toString(); // 2016-09-22
    

    Generate a String in your desired format by applying the formatter.

    String output = ld.format( f );
    

    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to java.time.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

    Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.