'Human readable date format in android java [duplicate]
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 1:[1]
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"
Solution 2:[2]
Try this:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 10);
System.out.println(DateFormat.format("yyyy-MM-dd hh:mm:ss", calendar).toString());
I'm using it. It will automatically remove 10 days from the current date.
Output: I/System.out: 2020-09-07 12:51:50
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | deHaar |
Solution 2 | Akshay Kalola |