android java 中人类可读的日期格式
Human readable date format in android java
例如
转换日期 是 2020-05-10 01:00:00
当前日期 是 2020-05-20 01:00:00
它应该显示 10 天前
我正在使用日历 class
Calendar cal = Calendar.getInstance();
您可以使用 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\"");
}
这输出
Sunday, 10 of May 2020 was (approximately) 10 days ago assuming Wednesday, 20 of May 2020 is "today"
试试这个:
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());
我正在使用它。它将自动从当前日期删除 10 天。
输出:I/System.out: 2020-09-07 12:51:50
例如
转换日期 是 2020-05-10 01:00:00 当前日期 是 2020-05-20 01:00:00
它应该显示 10 天前
我正在使用日历 class
Calendar cal = Calendar.getInstance();
您可以使用 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\"");
}
这输出
Sunday, 10 of May 2020 was (approximately) 10 days ago assuming Wednesday, 20 of May 2020 is "today"
试试这个:
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());
我正在使用它。它将自动从当前日期删除 10 天。
输出:I/System.out: 2020-09-07 12:51:50