Obtaining String in the format of DD-MON-YY from date

3.2k views Asked by At

I have the following code generating a random date, but I don't know how to display it in the form of DD-MON-YY (for example 12-NOV-12), which happens to be the SQL standard format for dates (i.e. in the end I plan on passing this data with JDBC into an oracle database).

GregorianCalendar gc = new GregorianCalendar();

gc.set(gc.YEAR,  randBetween(1900, 2015)); //randBetween creates a random number between the two

gc.set(gc.DAY_OF_YEAR, randBetween(1, gc.getActualMaximum(gc.DAY_OF_YEAR)));

//Mysterious formatting needed here

String s = //date would go here in the DD-MON-YY format

Anyway, point being I have tried many ways to format it and the closest I've got it to has been DD-MM-YY (for example 12-12-12). I was wondering if anyone knew of a short/easy way to achieve my goal without resorting to the primitive long way (if/switch-case statements).

1

There are 1 answers

5
Luiggi Mendoza On

Use SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
String s = sdf.format(gc.getTime());
System.out.println(s);

This is the part in the javadoc you were looking for:

Letter    Date or Time Component             Presentation      Examples
  M       Month in year (context sensitive)      Month      July; Jul; 07

Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

  • Letter M produces context-sensitive month names, such as the embedded form of names. If a DateFormatSymbols has been set explicitly with constructor SimpleDateFormat(String, DateFormatSymbols) or method setDateFormatSymbols(DateFormatSymbols), the month names given by the DateFormatSymbols are used.
  • Letter L produces the standalone form of month names.