Java – how to use the current date as the input of the function to get the month name
•
Java
How to create a function to get the current date and return the month name?
For example, string MonthName ("September 11, 2013"); When this function is called, the month name is returned
Solution
That should be no problem
It depends on the format of the date If you try February 1, 2011, it will work. Just change the string "mmmm D, yyyy" according to your needs Check whether this has all format modes
Moreover, the month is based on 0, so if you want January to be 1, you only need to return to the first month
private static int getMonth(String date) throws ParseException{ Date d = new SimpleDateFormat("MMMM d,yyyy",Locale.ENGLISH).parse(date); Calendar cal = Calendar.getInstance(); cal.setTime(d); int month = cal.get(Calendar.MONTH); return month + 1; }
If you want a month name, try this
private static String getMonth(String date) throws ParseException{ Date d = new SimpleDateFormat("MMMM d,Locale.ENGLISH).parse(date); Calendar cal = Calendar.getInstance(); cal.setTime(d); String monthName = new SimpleDateFormat("MMMM").format(cal.getTime()); return monthName; }
As I said, check all the format patterns of my published pages If you only need 3 character months, use "MMM" instead of "mmmm"
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
二维码