Java: convert string date to month name year (MMM yyyy)
•
Java
I'm new to Java I am trying to convert the date from string to MMM yyyy format (March 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 works normally But when I use it
String actualDate = "2016-03-20";
It doesn't work Help me how to solve this problem
Solution
Your format must match your input
2016-03-20
The format should be (use only the second simpledateformat object)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Complete 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 java-8
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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码