Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

java - How can I find the number of days between two Dates?

I have two Dates. How can I tell the difference between these two dates in days?

I have heard of SimpleDateFormat, but I don't know how to use it.

I tried this:

String fromdate = "Apr 10 2011";

SimpleDateFormat sdf;
sdf = new SimpleDateFormat("MMM DD YYYY"); 

sdf.parse(fromdate);

Calendar cal = Calendar.getInstance();
cal.setTime(sdf);

I also tried this:

String date1 = "APR 11 2011";
String date2 = "JUN 02 2011";
String format = "MMM DD YYYY";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();
int diffDays = (int) (diff / (24* 1000 * 60 * 60));
System.out.println(diffDays);

but I got the exception "Illegal pattern character 'Y'."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The other answers are correct but outdated.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

I suggest using standard ISO 8601 formats for your strings where possible. But in your case we need to specify a formatting pattern.

String input = "Apr 10 2011";

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu" );
LocalDate earlier = LocalDate.parse ( input , f );

DateTimeFormatter formatterOut = DateTimeFormatter.ofLocalizedDate ( FormatStyle.MEDIUM ).withLocale ( Locale.US );
String output = earlier.format ( formatterOut );

LocalDate later = earlier.plusDays ( 13 );

long days = ChronoUnit.DAYS.between ( earlier , later );

Dump to console.

System.out.println ( "from earlier: " + earlier + " to later: " + later + " = days: " + days + " ending: " + output );

from earlier: 2011-04-10 to later: 2011-04-23 = days: 13 ending: Apr 10, 2011


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...