问题
I have a String representing a date with format yyyy/mm/dd
and want to calculate the number of days between that day and today. How is this done?
So It may be something like
String aDate = "1934/05/24"
回答1:
Way to do this -
- Parse the date string to Date object using
SimpleDateFormat
. Get the date difference between todays date and parsed date.
long diff = d2.getTime() - d1.getTime();//in milliseconds
Now convert it to days, hours, minutes and seconds.
- 1000 milliseconds = 1 second
- 60 seconds = 1 minute
- 60 minutes = 1 hour
- 24 hours = 1 day
Other way using joda date time
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/mm/dd");
DateTime dt1 = formatter.parseDateTime(aDate);
And
Duration duration = new Duration(dt1 , new DateTime());
System.out.println("Days "+duration.getStandardDays()+" Hours "+duration.getStandardHours()+" Minutes "+duration.getStandardMinutes());
回答2:
The way to get the number of days between two dates with Joda-Time is to use Days.daysBetween
but the Days
class isn't part of the Java 8 java.time
package.
Instead, in Java 8, you can do this:
public static long daysBetween(ChronoLocalDate first, ChronoLocalDate second) {
return Math.abs(first.until(second, ChronoUnit.DAYS));
}
ChronoLocalDate
is an interface implemented by LocalDate
, so you can pass two LocalDate
s to this method and get the difference between them in days. (However, there are some caveats (see Using LocalDate instead) with using ChronoLocalDate
in place of LocalDate
in APIs. It might be better to just declare the parameters as LocalDate
s.)
回答3:
Use SimpleDateFormat with the proper mask and convert it to Date and then use a Calendar object to calculate the days between (like in this example: https://stackoverflow.com/a/8912994/79230).
来源:https://stackoverflow.com/questions/22510764/calculate-days-between-today-and-string-of-format-yyyy-mm-dd-in-java