Monday, December 4, 2017

Java 8: Three ways to calculate days between two dates

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class DateTest101 {

    public static void main(String[] args){
        String dt2 = "2017335";
        String dt1 = "2016335";
     
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyyDDD");
        LocalDate dat2 = LocalDate.parse(dt2, pattern);
        LocalDate dat1 = LocalDate.parse(dt1, pattern);
        System.out.println("dat2: "+dat2.toString()+", dat1: "+dat1);
     
        //Method 1
        long daysBetween1 = dat1.until(dat2, ChronoUnit.DAYS);
        System.out.println("daysBetween1: "+ daysBetween1);
     
        //Method 2
        long daysBetween2 = ChronoUnit.DAYS.between(dat1, dat2);
        System.out.println("daysBetween2: "+ daysBetween2);
     
        //Method 3
        long daysBetween3 = Duration.between(dat1.atStartOfDay(), dat2.atStartOfDay()).toDays();
        System.out.println("daysBetween3: "+ daysBetween3);
    }
}

Reference:

1. Calculate days between two dates in Java 8

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment