Languages
[Edit]
EN

Java - subtract hours from Date (java.util.Date)

7 points
Created by:
Joann-Calderon
383

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
    }
}

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - Date & Time

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join