问题
Is it possible to format JodaTime Date.
Here is the code:
private static LocalDate priorDay(LocalDate date1) {
do {
date1 = date1.plusDays(-1);
} while (date1.getDayOfWeek() == DateTimeConstants.SUNDAY ||
date1.getDayOfWeek() == DateTimeConstants.SATURDAY);
//System.out.print(date1);
return date1;
}
Here date1 returns as: 2013-07-02 but i would like as 02-JUL-13
Thanks in advance
回答1:
Is it possible to format JodaTime Date
Yes. You want DateTimeFormatter.
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yy")
.withLocale(Locale.US); // Make sure we use English month names
String text = formatter.format(date1);
That will give 02-Jul-13, but you can always upper-case it.
See the Input and Output part of the user guide for more information.
EDIT: Alternatively, as suggested by Rohit:
String text = date1.toString("dd-MMM-yy", Locale.US);
Personally I'd prefer to create the formatter once, as a constant, and reuse it everywhere you need it, but it's up to you.
回答2:
Check out the Joda DateTimeFormatter.
You probably want to use it via something like:
DateTime dt = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MMM-yy");
String str = fmt.print(dt);
This is a much better solution than the existing SimpleDateFormat class. The Joda variant is thread-safe. The old Java variant is (counterintuitively) not thread-safe!
来源:https://stackoverflow.com/questions/17450885/jodatime-date-format