Wednesday, March 21, 2018

Java: Convert String Date to Month Name Year (MMM yyyy)




I am new to Java. I am trying to convert date from string to MMM yyyy format (Mar 2016). I tried this



Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy");
String month_name = month_date.format(cal.getTime());
System.out.println("Month :: " + month_name); //Mar 2016



It is working fine. But when I use



String actualDate = "2016-03-20";


It is not working. Help me, how to solve this.


Answer



Your format must match your input



for 2016-03-20




the format should be (just use a second SimpleDateFormat object)



SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");





Full answer




SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String actualDate = "2016-03-20";

Date date = sdf.parse(actualDate);

String month_name = month_date.format(date);
System.out.println("Month :" + month_name); //Mar 2016






Using java.time



String actualDate = "2016-03-20";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MMM yyyy", Locale.ENGLISH);
LocalDate ld = LocalDate.parse(actualDate, dtf);
String month_name = dtf2.format(ld);

System.out.println(month_name); // Mar 2016

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...