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());
CodePudding user response:
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());
CodePudding user response:
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);