英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论