Convert int months to names

Hi Friends,

Is there a direct way to convert months (int) to months(name-wise).

Example, if someone enters 1 ,it should display it as Jan.

import java.util.*;

import java.text.*;

publicclass jDate{

publicstaticvoid main ( String args [ ] )

{

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

Calendar cal = Calendar.getInstance ( ) ;

cal.set(2007,02,27);

System.out.println ("Date: " + sdf.format (cal.getTime())) ;

}

}

Actual Output: Date: 2007-03-27

ExpectedOutput: Date: Feb 27,2007

Or do I need to do some processing like:

String[] months = {"Jan","Feb",...."Dec"};

Thanks

[1136 byte] By [java80a] at [2007-11-26 19:50:52]
# 1
A simple way would be to just have an array. A more flexible way (usable in different locales) would be to have two SimpleDateFormats--one that parses the month number to a Date and the other that formats the month of that Date into a String.
jverda at 2007-7-9 22:40:30 > top of Java-index,Java Essentials,New To Java...
# 2
String monthName = new DateFormatSymbols().getMonths()[month - 1];
DrClapa at 2007-7-9 22:40:30 > top of Java-index,Java Essentials,New To Java...
# 3
Thanks Guys,That works like a charm DrClap.
java80a at 2007-7-9 22:40:30 > top of Java-index,Java Essentials,New To Java...
# 4

Hi,

I got that working like this:

Format sdf = new SimpleDateFormat ( "MMM dd, yyyy" ) ;

Calendar cal = Calendar.getInstance ( ) ;

cal.set(2007,02,27);

String date1 = sdf.format(cal.getTime());

But it asks to format the date output like this:

Display date as 20 character positions( left justified )

How to do that?Should i use a char[] or some Stringf functionalities and how to get that justification,any help?

java80a at 2007-7-9 22:40:30 > top of Java-index,Java Essentials,New To Java...
# 5
What is asking you to format it like that?
floundera at 2007-7-9 22:40:30 > top of Java-index,Java Essentials,New To Java...
# 6
Won't your date1 string be 12 characters long always? Then add 8 spaces?Or more generally, if date1 has length X, add 20-X spaces.
DrLaszloJamfa at 2007-7-9 22:40:30 > top of Java-index,Java Essentials,New To Java...
# 7
> How to do that?Here's one way:Calendar c = Calendar.getInstance();System.out.printf("%-20s...\n", String.format("%1$tb %1$td, %1$tY", c));
yawmarka at 2007-7-9 22:40:30 > top of Java-index,Java Essentials,New To Java...