Makky Makky - 3 months ago 9
Java Question

Changing Java Date one hour back

I have a Java date object:

Date currentDate = new Date();


This will give the current date and time. Example:

Thu Jan 12 10:17:47 GMT 2012


Instead, I want to get the date, changing it to one hour back so it should give me:

Thu Jan 12 09:17:47 GMT 2012


What would be the best way to do it?

Answer
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.HOUR, -1);
Date oneHourBack = cal.getTime();

You can remove the second line if you're always using the current time.

Comments