Java Nerd
Java Nerd

Reputation: 187

"How to format LocalDate with Custom Pattern" in Java

I am new to JodaTime and learning it to my own. Actually what I want is to just format the LocateDate in my own format. My format is "dd-mm-yyyy"

I have method that calculates the difference with two dates:

private void sampleDaysDifference() {
    DateTime todayDate = getLocalTodayDate();
    DateTime dateAfterTwoDays = getDateAfterTwoDays();

    //get the days difference
    int differenceOfDates = Days.daysBetween(todayDate, dateAfterTwoDays).getDays();
    Log.e("logX","differenceOfDates: " + differenceOfDates);

}

To get the today date I am using:

private DateTime getLocalTodayDate() {
    LocalDate now = LocalDate.now();
    DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_FORMAT);
    return fmt.parseDateTime(now.toString());//return the today date
}

and to get the date after two days:

private DateTime getDateAfterTwoDays() {
    LocalDate now = LocalDate.now();
    DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_FORMAT);
    return fmt.parseDateTime(now.plusDays(2).toString());//return date after two days
}

The problem is that I have no idea how to format date using JodaTime, can somebody please tell me how to format a JodaTime LocalDate!

Actually my app is crashing with the stacktrace:

  Caused by: java.lang.IllegalArgumentException: Invalid format: "16 January, 2019" is malformed at " January, 2019"

Upvotes: 0

Views: 4688

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40068

You are almost there but just the pattern is wrong that you specified, change "dd-mm-yyyy" to this "dd-MM-yyyy" docs-for-patterns

Simple Example

System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd-MM-yyyy")));   //16-01-2019

From Joda DateTimeFormatter joda-docs

The pattern syntax is mostly compatible with java.text.SimpleDateFormat

Upvotes: 3

Related Questions