-2

I'm trying to make a code that tells me how many days left for me to go college, but I am not able to do it with the current date. I can easily make it by setting a date, but I want the current date, so I have to use the calendar method, but can't do math using it. My code:

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Calendar calendar = Calendar.getInstance();
    Date start = sdf.parse("10/06/2022");
    System.out.println(start - calendar.getTime());
  • 1
    Does this answer your question? [Java Calendar: Getting Difference Between Two Dates/Times - Off by One](https://stackoverflow.com/questions/13198609/java-calendar-getting-difference-between-two-dates-times-off-by-one) – pringi Mar 02 '22 at 13:40
  • 1
    I recommend you don’t use `SimpleDateFormat`, `Calendar` and `Date`. Those classes are poorly designed and long outdated, the first in particular notoriously troublesome. Instead use `LocalDate`, `DateTimeFormatter` and`ChronoUnit.DAYS`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 02 '22 at 16:27
  • Does this answer your question? [Calculate days between two Dates in Java 8](https://stackoverflow.com/questions/27005861/calculate-days-between-two-dates-in-java-8) – Ole V.V. Mar 02 '22 at 16:33
  • 1
    No one should use the JDK 1.0 vintage Calendar class. Prefer the classes in java.util.time package. – duffymo Mar 03 '22 at 11:16
  • 1
    @duffymo JDK 1.1 to be precise. Still more than 25 years old, and still replaced by java.time 8 years ago this month. You are 100 % correct, that class is not to be used (repeating myself). – Ole V.V. Mar 03 '22 at 11:25

3 Answers3

4

tl;dr

ChronoUnit.DAYS.between( 
    LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) , 
    LocalDate.parse( "10/06/2022" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) 
) 

Details

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Date/Calendar.

Also, you are attempting to use a date-time class representing a date with time-of-day as seen in UTC (offset of zero) to hold a date-only value. Square peg, round hole.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate graduationDate = LocalDate.parse( "10/06/2022" , f ) ;

Determine today's date. That requires a time zone. For any given moment, the date varies around the globe by time zone.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;  // Or ZoneId.systemDefault()
LocalDate today = LocalDate.now( z ) ;

Calculate elapsed time using java.time.temporal.ChronoUnit.

long days = ChronoUnit.DAYS.between( today , graduationDate ) ;

See this code run live at IdeOne.com.

graduationDate: 2022-06-10
today: 2022-03-05
days: 97

Tip: Learn about the ISO 8601 standard for exchanging date-time values as text.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • +1. And, just a purely stylistic comment for the OP, I would statically import `ChronoUnit.DAYS` so that the code simply read as `DAYS.between` etc. – David Conrad Mar 03 '22 at 23:38
0
    Calendar calendar = Calendar.getInstance();   
    Calendar collegeDate = Calendar.getInstance();
    collegeDate.set(Calendar.DATE,10);
    collegeDate.set(Calendar.MONTH, 5);
    collegeDate.set(Calendar.YEAR, 2022);
    System.out.println(Duration.between(calendar.toInstant(), collegeDate.toInstant()).toDays());
  • 5
    If you know to use Duration and toInstant(), why are you using Calendar? Just stick with proper, modern java.time classes. – David Conrad Mar 02 '22 at 14:54
0

You can try this

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Calendar calendar = Calendar.getInstance();
        Date start = sdf.parse("10/06/2022");

        long dif = Math.abs(calendar.getTimeInMillis() - start.getTime());
        long result = TimeUnit.DAYS.convert(dif, TimeUnit.MILLISECONDS);

        System.out.println(result);
Ksu
  • 121
  • 1
  • 1
  • 6
  • 3
    There is absolutely no reason in 2022 to be using Calendar, Date, or SimpleDateFormat. – David Conrad Mar 02 '22 at 14:53
  • @DavidConrad The question does not have a detailed description. Perhaps the author wants to use this code in his android application. If so, then this is the best solution, because for example the Duration class requires a minimum of android version 8 to work. – Leonid Mar 02 '22 at 15:19
  • 2
    @Leonid Not so. java.time is available for lower Android versions through [desugaring](https://developer.android.com/studio/write/java8-support-table) (also there is no mention of Android in the question, so an answer assuming it’s for Android is either inappropriate or should at least state clearly that the answer is for lower version Android only). As this answer stands, it is likely to lead more users astray than on a good track. – Ole V.V. Mar 02 '22 at 16:30
  • 1
    The answer is also wrong. It assumes there are 24 hours in a day. This is not always the case. – Ole V.V. Mar 02 '22 at 16:30
  • @DavidConrad as I said, it's a countdown to my college start, meaning I'm learning the basics of java :) – Afonso Britto Mar 02 '22 at 16:52
  • 2
    @AfonsoBritto Neither `SimpleDateFormat`, `Calendar` nor `Date` belongs to the basics of Java. They belong to the outdated and troublesome Java classes that everyone should avoid and learners even more so. – Ole V.V. Mar 03 '22 at 03:21
  • 1
    @AfonsoBritto [Sun Microsystems](https://en.wikipedia.org/wiki/Sun_Microsystems), [Oracle Corp](https://en.wikipedia.org/wiki/Oracle_Corporation), and the [JCP](https://en.wikipedia.org/wiki/Java_Community_Process) community all gave up on those terrible legacy date-time classes when they unanimously adopted [JSR 310](https://jcp.org/en/jsr/detail?id=310). – Basil Bourque Mar 03 '22 at 06:59