Reputation: 588
I need to convert date format into NEW_FORMAT date format. I want to show like this June 28,2016 ,but its showing January irrespective of any month number I pass. Please check where I am missing..
public class DateClass {
public static void main(String[] args)
{
final String OLD_FORMAT = "yyyy-mm-dd";
final String NEW_FORMAT = "MMMM dd,yyyy";
String oldDateString = "2016-06-28";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d;
try {
d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
System.out.println(""+newDateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Upvotes: 1
Views: 134
Reputation: 340230
Use modern java.time classes.
Specify a Locale
to determine the human language and cultural norms to be used in localizing the name of the month.
String output =
LocalDate
.parse( "2025-01-23" ) // Standard ISO 8601 format can be directly parsed, no need to specify a formatting pattern.
.format(
DateTimeFormatter
.ofPattern( "MMMM dd, uuuu" )
.withLocale( Locale.of( "en" , "US" ) ) // English language, United States cultural norms.
) ;
Upvotes: 1
Reputation: 7678
In java, mm represents as minuets and MM represents as Month, so you have to change your code as
final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "MMMM dd,yyyy";
String oldDateString = "2016-06-28";
Upvotes: 2
Reputation: 2006
change this one
final String OLD_FORMAT = "yyyy-mm-dd";
to
final String OLD_FORMAT = "yyyy-MM-dd";
Upvotes: 2
Reputation: 9974
You're using mm
in OLD_FORMAT
which stands for minute. You want to have MM
which stands for month.
Therefore your OLD_FORMAT
should be yyyy-MM-dd
.
The minute is set to 0
in your case therefore the month is January.
Upvotes: 2
Reputation: 17622
your OLD_FORMAT
is wrong, it should be "yyyy-MM-dd"
. Here small m
should be replaced by capital M
, since small m
represents minutes and M
represents month of year, and while parsing using OLD_FORMAT
, date is getting parsed wrongly.
Upvotes: 4