android-studiodatetimeandroid-dateandroid-jodatime

How can I change my date format using org.joda.time.LocalDate in android studio?


Basically, I want to get the date of Monday from the current day of the week. eg: today is Tuesday and I want a Monday date, I'll get that required date from the following code lines:

 val now = LocalDate()
 val monday: LocalDate = now.withDayOfWeek(DateTimeConstants.MONDAY)
        mondayDate = monday.toString()
       

But the problem is that I'm getting date format as 2021-05-24 and I want the date in such format 24-5-2021. Now how to change the date format to get the required date format.


Solution

  • What you need is a formatter.

        DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("d-M-y");
        
        LocalDate now = new LocalDate();
        LocalDate monday = now.withDayOfWeek(DateTimeConstants.MONDAY);
        String mondayDate = monday.toString(dateFormatter);
        System.out.println(mondayDate);
    

    Output is what you asked for:

    24-5-2021