您可以使用java.time,它在较低的Android API 中受支持,因为现在有API desugaring in Android。
有一个区域感知类 (java.time.ZonedDateTime) 和一个偏移感知类 (java.time.OffsetDateTime),但您的示例 String 仅包含与 GMT / UTC 的偏移量。这就是为什么我会使用 OffsetDateTime 来解析确切的时间然后添加一天。
这是一个简单的示例,它定义了一个格式化程序,它解析给定的String 并将其用于输出:
public static void main(String[] args) {
// example String
String date = "Fri Dec 18 23:00:00 GMT+02:00 2020";
// create a formatter that is able to parse and output the String
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss OOOO uuuu",
Locale.ENGLISH);
// parse the String using the formatter defined above
OffsetDateTime odt = OffsetDateTime.parse(date, dtf);
System.out.println("OffsetDateTime parsed is\t" + odt.format(dtf));
// add a day to the date part
OffsetDateTime dayLater = odt.plusDays(1);
System.out.println("Adding a day results in\t\t" + dayLater.format(dtf));
}
这个输出
OffsetDateTime parsed is Fri Dec 18 23:00:00 GMT+02:00 2020
Adding a day results in Sat Dec 19 23:00:00 GMT+02:00 2020
如果您只对输出日期感兴趣(没有时间部分或偏移量),那么这些类中还有另一个方便的功能,即轻松提取日期或时间部分。您可以使用OffsetDateTime 执行以下操作,例如:
// extract the part that only holds information about day of month, month of year and year
LocalDate dateOnly = odt.toLocalDate();
// print the default format (ISO standard)
System.out.println(dateOnly);
// or define and use a totally custom format
System.out.println(dateOnly.format(
DateTimeFormatter.ofPattern("EEEE, 'the' dd. 'of' MMMM uuuu",
Locale.ENGLISH)
)
);
那会输出
2020-12-18
Friday, the 18. of December 2020
如果您正在处理DatePicker datePicker,您可以通过getYear()、getMonth() 和getDayOfMonth() 接收选定的值,然后创建一个
LocalDate localDate = LocalDate.of(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth());
然后通过localDate.plusDays(1);简单地添加一天