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 (ie 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).
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 constructorSimpleDateFormat(String, DateFormatSymbols)
or methodsetDateFormatSymbols(DateFormatSymbols)
, the month names given by theDateFormatSymbols
are used.- Letter L produces the standalone form of month names.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.