EN
Java - subtract hours from Date (java.util.Date)
7
points
Hi, today I would like to show you how to subtract hours from Date in Java.
Quick solution:
Date dateNow = new Date();
LocalDateTime localDate = LocalDateTime
.ofInstant(dateNow.toInstant(), ZoneId.systemDefault()).minusHours(2);
Date dateSubtracted = Date.from(localDate.atZone(ZoneId.systemDefault()).toInstant());
System.out.println(dateNow); // Sat Dec 19 16:42:12 CET 2020
System.out.println(dateSubtracted); // Sat Dec 19 14:42:12 CET 2020
In above example we subtracted 2 hours from current time.
Full example with imports:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class Example {
public static void main(String[] args) {
Date dateNow = new Date();
LocalDateTime localDate = LocalDateTime
.ofInstant(dateNow.toInstant(), ZoneId.systemDefault()).minusHours(2);
Date dateSubtracted = Date.from(localDate.atZone(ZoneId.systemDefault()).toInstant());
System.out.println(dateNow); // Sat Dec 19 16:42:12 CET 2020
System.out.println(dateSubtracted); // Sat Dec 19 14:42:12 CET 2020
}
}