Issue
i have a script that show the different of the dates but the one i need it is to get 0 day if 'tglkembali' is lower than 'tempo' but the script i type is calculating the both ways
try{
String tglsatu = tempo.getText();
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
Date tglAwal = (Date) date.parse(tglsatu);
String tgldua = tglKembali.getText();
Date tglAkhir = (Date) date.parse(tgldua);
long bedaHari = tglAkhir.getTime() - tglAwal.getTime();
terlambat.setText(TimeUnit.MILLISECONDS.toDays(bedaHari) + " hari");
}catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
Solution
java.time
try {
String tglSatu = "2019-01-07";
LocalDate tglAwal = LocalDate.parse(tglSatu);
String tglDua = "2019-01-18";
LocalDate tglAkhir = LocalDate.parse(tglDua);
long bedaHari = ChronoUnit.DAYS.between(tglAwal, tglAkhir);
if (bedaHari < 0) {
bedaHari = 0;
}
System.out.println("" + bedaHari + " hari");
} catch (DateTimeParseException dtpe){
System.out.println(dtpe.getMessage());
}
When the days are in the expected order, as in the snippet above, the output should agree with yours:
11 hari
However, If I change this line so the dates are swapped:
String tglDua = "2018-12-29";
Now the output from my code is what you requested:
0 hari
Corner case: When I say the output is the same in the former case, this is only most often true. You used Date.getTime
and TimeUnit.MILLISECONDS.toDays
, so you performed a conversion from milliseconds to days assuming a day is always 24 hours long. This is not always the case. For example, in the spring when summer time (DST) begins in some countries, the day is typically only 23 hours, which will cause your code to count a day too few. The LocalDate
class that I use neither has got time of day nor time zone, so evades this problem.
The other reason why I am using java.time, the modern Java date and time API, is it is generally much nicer to work with than the old date and time classes, including DateFormat
, SimpleDateFormat
and Date
. Those had some design problems, and there’s no reason why we should still struggle with them.
An alternative option is to compare the dates using isBefore
or isAfter
and show a message if they are not in the expected order. For example (with assistance from Google Translate):
if (tglAkhir.isBefore(tglAwal)) {
System.out.println("Tanggal berada dalam urutan yang salah");
} else {
long bedaHari = ChronoUnit.DAYS.between(tglAwal, tglAkhir);
System.out.println("" + bedaHari + " hari");
}
Links:
- Oracle tutorial: Date Time explaining how to use java.time.
- Google Translate.
Answered By - Ole V.V.
Answer Checked By - Marie Seifert (JavaFixing Admin)