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!
LocalDate.parse( "22/09/2016" , DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )
.format( DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )
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.
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 );
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.