如何解决如何获取当前日期和从当前日期算起的未来30天的日期
开发人员,希望您一切都好,我正在尝试将当前日期定为2020年9月16日,然后在此之后想要获得下一个30天的日期。抱歉,我是新来的,所以没有正确的问题。如果您有解决方案,请与我们分享,或者有任何疑问,请与我们联系。预先感谢。
解决方法
我建议您使用modern java.time
日期时间API和相应的格式API(软件包java.time.format
)来完成此操作。从 Trail: Date Time 了解有关现代日期时间API的更多信息。 java.util
日期时间API和SimpleDateFormat
已过时且容易出错。
如果您的Android API级别仍不兼容Java8,请选中How to use ThreeTenABP in Android Project和Java 8+ APIs available through desugaring。
使用现代的日期时间API进行以下操作:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Define a formatter for your custom pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
// I've used the default time-zone of your JVM. As per your requirement,you can
// change to different time-zone e.g as shown in the commented code
// LocalDate today = LocalDate.now(ZoneId.of("Europe/London"));
LocalDate today = LocalDate.now();// Same as LocalDate.now(ZoneId.systemDefault())
// Print in default pattern i.e. in the pattern returned by LocalDate.toString()
System.out.println("Today in the default pattern: " + today);
// Print in the defined custom pattern
System.out.println("Today in dd/MM/yyyy pattern: " + today.format(formatter));
// After 30 days from today
LocalDate after30Days = today.plusDays(30);
System.out.println("After 30 days: " + after30Days.format(formatter));
// After 30 days from today
LocalDate afterOneMonth = today.plusMonths(1);
System.out.println("After one month: " + afterOneMonth.format(formatter));
}
}
输出:
Today in the default pattern: 2020-09-16
Today in dd/MM/yyyy pattern: 16/09/2020
After 30 days: 16/10/2020
After one month: 16/10/2020
,
这是使用java.time
的方法,现在可以通过Android API Desugaring使用它来降低Android API版本:
public static void main(String[] args) {
// get the date of today
LocalDate today = LocalDate.now();
// get the date that is 30 days later
LocalDate thirtyDaysInFuture = today.plusDays(30);
// get the date a month later (not necessarily the same date as 30 days later)
LocalDate aMonthInFuture = today.plusMonths(1);
// define a desired format for output (use log(...) in Android instead of System.out)
DateTimeFormatter customDtf = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// print the results using the formatter defined above
System.out.println("Today:\t\t\t" + today.format(customDtf));
System.out.println("Thirty days later:\t" + thirtyDaysInFuture.format(customDtf));
System.out.println("One month later:\t" + aMonthInFuture.format(customDtf));
}
输出:
Today: 16/09/2020
Thirty days later: 16/10/2020
One month later: 16/10/2020
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。