How to find the number of days between two dates in java or groovy?

后端 未结 9 1783
走了就别回头了
走了就别回头了 2020-12-09 19:25

I have a method which uses following logic to calculate difference between days.

long diff = milliseconds2 - milliseconds1;
long diffDays = diff / (24 * 60 *         


        
相关标签:
9条回答
  • 2020-12-09 19:55

    In groovy all you need is:

    date2 - date1
    

    which returns an integer representing the number of days between the two dates.

    Or if you need to guard against reversal of order between the two Date instances (the operation returns negative numbers when the first operand is earlier than the second):

    Math.abs(date2 - date1)
    

    The above examples use the groovy date.minus(date) operator implementation which returns the number of days between the two dates.

    Example groovy shell session:

    $ groovysh
    Groovy Shell (2.4.8, JVM: 1.8.0_111)
    Type ':help' or ':h' for help.
    
    groovy:000> x = new Date(1486382537168)
    ===> Mon Feb 06 13:02:17 CET 2017
    
    groovy:000> y = new Date(1486000000000)
    ===> Thu Feb 02 02:46:40 CET 2017
    
    groovy:000> x - y
    ===> 4
    

    or if you need a method:

    int daysBetween(date1, date2) {
        Math.abs(date2 - date1)
    }
    
    0 讨论(0)
  • 2020-12-09 20:02

    Find out the number of days in between two given dates:

    @Test
    
    public class Demo3 {
    
        public static void main(String[] args) {
            String dateStr ="2008-1-1 1:21:28";
            String dateStr2 = "2010-1-2 1:21:28";
            SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
            SimpleDateFormat format2 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
            try {
                Date date2 = format.parse(dateStr2);
                Date date = format.parse(dateStr);
    
                System.out.println("distance is :"+differentDaysByMillisecond(date,date2));
            }catch(ParseException e ){
                e.printStackTrace();
            }
        }
    
    //get Days method
    
        private static int differentDaysByMillisecond(Date date, Date date2) {
            return (int)((date2.getTime()-date.getTime())/1000/60/60/24);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-09 20:05
    Date.metaClass.calculateDays = { Date offset = new Date() ->            
        Long result = null
        Date date = delegate
        use(groovy.time.TimeCategory) {
            result = (offset - date).days as Long
        }            
        result            
    }
    

    example of use:

    def sdf = new java.text.SimpleDateFormat("yyyy.MM.dd")
    
    sdf.lenient = false
    
    Date date = sdf.parse("2015.10.02")
    
    println date.calculateDays() 
    
    println date.calculateDays(sdf.parse("2015.11.02"))
    
    0 讨论(0)
  • 2020-12-09 20:11

    just parse 9th feb 2011 & 19th feb 2011 into dates using SimpleDateFormat and convert it to start & end millis and apply your calculation

    0 讨论(0)
  • 2020-12-09 20:14
      GregorianCalendar cal1 = new GregorianCalendar(2011,2,9); 
      GregorianCalendar cal2 = new GregorianCalendar(2011,2,19); 
      long ms1 = cal1.getTime().getTime(); 
      long ms2 = cal2.getTime().getTime(); 
      long difMs = ms2-ms1; 
      long msPerDay = 1000*60*60*24; 
    
      double days = difMs / msPerDay;
    
    0 讨论(0)
  • 2020-12-09 20:15

    For the groovy solution you asked for you should consider using this:

    use(groovy.time.TimeCategory) {
       def duration = date1 - date2
       println "days: ${duration.days}, Hours: ${duration.hours}"
    }
    

    It's very easy to understand and extremely readable. You asked for a example how this can be used in an easy method which calculates the days between two dates. So here is your example.

    class Example {
    
        public static void main(String[] args) {
            def lastWeek = new Date() - 7;
            def today = new Date()
    
            println daysBetween(lastWeek, today)
        }
    
        static def daysBetween(def startDate, def endDate) {
            use(groovy.time.TimeCategory) {
                def duration = endDate - startDate
                return duration.days
            }
        }
    }
    

    If you run this example it will print you 7. You can also enhance this method by using before() and after() to enable inverted dates.

    0 讨论(0)
提交回复
热议问题