human-readable

Human readable date format in android java


For Example

Date to convert is 2020-05-10 01:00:00 Current Date is 2020-05-20 01:00:00

It should show 10 days ago

I'm using Calendar class

Calendar cal = Calendar.getInstance();


Solution

  • You can use java.time for this, it is now available to lower API versions in Android due to Android API Desugaring:

    public static void main(String[] args) {
        // create the datetime ten days ago
        LocalDateTime tenDaysBefore = LocalDateTime.of(2020, 5, 10, 1, 0, 0);
        // create the one that is used as "today"
        LocalDateTime current = LocalDateTime.of(2020, 5, 20, 1, 0, 0);
        // calculate the period between them (this only considers the date part)
        Period period = Period.between(tenDaysBefore.toLocalDate(), current.toLocalDate());
        // define a formatter for human readable output
        DateTimeFormatter outputDtf = DateTimeFormatter.ofPattern("EEEE, dd 'of' MMMM uuuu",
                                                                    Locale.ENGLISH);
        // and output a meaningful sentence
        System.out.println(tenDaysBefore.format(outputDtf) + " was (approximately) "
                            + period.getDays() + " days ago assuming "
                            + current.format(outputDtf) + " is \"today\"");
    }
    

    This outputs

    Sunday, 10 of May 2020 was (approximately) 10 days ago assuming Wednesday, 20 of May 2020 is "today"