-1

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());
stefanosn
  • 3,264
  • 10
  • 53
  • 79
  • 1
    Use Calendar instance to get current date while creating the notification and add one day to get next day date. SimpleDateFormat is formatter to get date you need either Date or Calendar instance. – 333 Oct 18 '20 at 13:52
  • Thanks for your answer. Using Date then how is this possible? I do not want to use Calendar. – stefanosn Oct 18 '20 at 14:06
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Oct 18 '20 at 15:23
  • Under the linked original question I’m immodest enough to recommend [my own answer](https://stackoverflow.com/a/63698604/5772882). – Ole V.V. Oct 18 '20 at 15:26
  • Why don’t you want to use `Calendar`? The `Calendar` class is poorly designed and long outdated, I certainly don’t recommend using it. Asking because on the other hand it’s not more poorly designed or longer outdated than the `Date` or `SimpleDateFormat` classes, rather the other way around. – Ole V.V. Oct 18 '20 at 15:28

2 Answers2

1

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);
333
  • 345
  • 2
  • 7
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);
Omid.N
  • 824
  • 9
  • 19