Reputation: 7746
For some reason this is outputting a numerical value of around 16348. When the first and last dates value are 0110 and 0201 respectively. How come I am not getting a day value?
import java.util.Scanner;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
public class Project3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String firstDate = input.next(), lastDate = input.next();
try {
Date date1 = new SimpleDateFormat("MMdd").parse(firstDate);
Date date2 = new SimpleDateFormat("MMdd").parse(lastDate);
System.out.println(Project3.days(date1, date2));
} catch (Exception e) {
//
}
}
public static long days(Date startDate, Date endDate) {
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
long daysBetween = 0;
while(start.before(end)) {
start.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
}
Upvotes: 0
Views: 302
Reputation: 340049
ChronoUnit.DAYS.between(
MonthDay.parse( "0110" , DateTimeFormatter.ofPattern( "MMdd" ) ).atYear( 2017 ) ,
MonthDay.parse( "0201" , DateTimeFormatter.ofPattern( "MMdd" ) ).atYear( 2017 )
)
If possible, change your text format to comply with the ISO 8601 standard. The month-day format is --MM-DD such as --01-10
for the tenth of January.
MonthDay
Use the MonthDay
class to represent a month-day.
MonthDay md1 = MonthDay.parse( "--01-10" );
MonthDay md2 = MonthDay.pares( "--02-01" );
Or use a DateTimeFormatter
.
MonthDay md = MonthDay.parse(
"0110" ,
DateTimeFormatter.ofPattern( "MMdd" )
)
LocalDate
To calculate days, you must apply a year. Because of Leap Year and February 29th, we cannot accurately calculate elapsed days without the context of a year.
LocalDate ld1 = md1.atYear( 2017 );
LocalDate ld2 = md2.atYear( 2017 );
ChronoUnit
Get elapsed days with ChronoUnit
.
long days = ChronoUnit.DAYS.between( ld1 , ld2 );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Upvotes: 0
Reputation: 201517
You forgot to call Calendar.setTime(Date)
on the end
,
Calendar end = Calendar.getInstance();
end.setTime(endDate); // <-- like so.
Upvotes: 3