Get name of the month from the number of the month Java

Many times we need to use month name to display date in well formed manner. I encounter this issue while developing Android application that use Android datepicker. It returns me the number of the month between 0 to 11 [I thought it would be 1-12]. But for display I need the name of the month.

For that I found one Java class that can convert integer number to name [I am too lazy to write an array that can do the work for me]. And the class DateFormatSymbols can convert it the following way. I just made a method so everyone[like me !!!] can copy-paste it to their project.

public String getMonthForInt(int num) {
    String month = "wrong";
    DateFormatSymbols dfs = new DateFormatSymbols();
    String[] months = dfs.getMonths();
    if (num >= 0 && num <= 11 ) {
        month = months[num];
    }
    return month.toLowerCase();
}

Get Date and Time in Android

In Android, to get time and date you have to first create the object of calender then you can format it using simpledateformat class according to your need. At last it returns you a date and time as per your format in String return type.

Here is the sample code for getting date and time as string.

Code :

public String getDateTime()	{
	Calendar c = Calendar.getInstance(); 
	SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
	return df.format(c.getTime());
}