Вопрос

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"
Это было полезно?

Решение

Way to do this -

  1. Parse the date string to Date object using SimpleDateFormat.
  2. Get the date difference between todays date and parsed date.

    long diff = d2.getTime() - d1.getTime();//in milliseconds

  3. 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());

Другие советы

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 LocalDates 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 LocalDates.)

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).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top