安卓如何使用SimpleDateFormat添加新日期

huangapple go评论67阅读模式
英文:

Android how to add new date using SimpleDateFormat

问题

以下是您的翻译内容:

这是我在我的安卓应用中使用 Java 获取当前日期的代码。日期应该显示在我的通知中。通知将在一天后显示。我需要获取新的日期,日期要加一天,但不使用日历选项。这可能吗?

String OnedaylaterDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
英文:

This is the code i use to get current date in my android app using java. The date should show up in my notification. The notification will show up one day later. I need to get new date plus one day without using calendar options. Is it possible?

String OnedaylaterDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());

答案1

得分: 1

自从您不想使用Calendar实例后,您可以使用LocalDate。附注:LocalDate从Java 8开始支持。

LocalDate date = LocalDate.now().plusDays(1);
System.out.println("Adding one day to current date: " + date);
英文:

Since you don't want to use the Calendar instance you can use LocalDate. PS:- LocalDate is supported from Java 8.

LocalDate date =  LocalDate.now().plusDays(1);
System.out.println("Adding one day to current date: "+date);

答案2

得分: 1

你不应再使用java.util.Date,因为它已被java.time包取代。此外,java.util.Date中的方法已被Calendar中的方法所取代,例如Date.getDay(),它返回一周中的星期几,被Calendar.get(Calendar.DAY_OF_WEEK)所替代。但如果您仍希望使用Date类,以下是示例:

Date afterOneDay = new Date(date.getYear(), date.getMonth(), date.getDate() + 1,
                            date.getHours(), date.getMinutes(), date.getSeconds());

而使用java.time.*的示例如下:

LocalDateTime time = LocalDateTime.now();
        
LocalDateTime afterOneDay = time.plusDays(1);
英文:

You should no longer use java.util.Date because it was replaced with the java.time package. Moreover, the methods in java.util.Date were replaced with the ones in Calendar, for example Date.getDay() which returns the number of the day f the week were replaced with Calendar.get(Calendar.DAY_OF_WEEK);. But if you still want to do it with Date class, here it is :

Date afterOneDay=Date.UTC(date.getYear(), date.getMonth(), date.getDate() + 1,  //plus one
                                 date.getHours(),date.getMinutes(),date.getSeconds());

Here is how you would do it with java.time.*:

LocalDateTime time=LocalDateTime.now();
    
LocalDateTime afterOneDay=time.plusDays(1);

huangapple
  • 本文由 发表于 2020年10月18日 21:49:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64414094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定