Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get month name using current date as input in function

Tags:

java

date

android

How do I create a function which take current date and return month name?
I have only date its not current date it can be any date like 2013/4/12 or 23/8/8.

Like String monthName("2013/9/11");
when call this function return the month name.

like image 211
user2762662 Avatar asked Sep 14 '13 20:09

user2762662


People also ask

Which function returns the name of the month from selected date?

The MONTHNAME() function returns the name of the month for a given date.

How do I turn a date into a month in Excel?

Microsoft Excel's TEXT function can help you to convert a date to its corresponding month name or weekday name easily. In a blank cell, please enter this formula =TEXT(A2,"mmmm"), in this case in cell C2. , and press the Enter key.

How do I get the month name from a number in Python?

To get the month name from a number in Python, the easiest way is with strftime() and passing “%M”. You can also use the calendar module and the month_name() function.


1 Answers

This should be fine.

It depends on the format of date. If you try with February 1, 2011 it would work, just change this string "MMMM d, yyyy" according to your needs. Check this for all format patterns.

And also, months are 0 based, so if you want January to be 1, just return month + 1

   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 month name try this

private static String getMonth(String date) throws ParseException{  
    Date d = new SimpleDateFormat("MMMM d, yyyy", 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 web page I posted for all format patterns. If you want only 3 characters of month, use "MMM" instead of "MMMM"

like image 137
Boy Avatar answered Sep 24 '22 01:09

Boy