Calculate days between today and string of format yyyy/mm/dd in Java [duplicate]

久未见 提交于 2020-01-05 12:13:43

问题


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 -

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



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




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!