Mendapatkan Selisih Hari diantara tanggal pada Java


Langsung saja run kode berikut ini :

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String date1 = "2017-01-01";
        String date2 = "2017-01-05";
        Date date1a = null;
        Date date2a = null;
        try {

            date1a = formatter.parse(date1);
            date2a = formatter.parse(date2);
            System.out.println("Tanggal 1 : " + date1);
            System.out.println("------");
            System.out.println("Tanggal 2 : " + date2);
            //diff in msec
            long diff = date2a.getTime() - date1a.getTime();

            //diff in days
            long days = diff / (24 * 60 * 60 * 1000);
            System.out.println(days + " Hari");

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

0 comments: