Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jodatime date format

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

like image 346
user2501165 Avatar asked Nov 29 '22 01:11

user2501165


2 Answers

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.

like image 95
Jon Skeet Avatar answered Dec 06 '22 00:12

Jon Skeet


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!

like image 38
Brian Agnew Avatar answered Dec 06 '22 02:12

Brian Agnew