Changing Java Date one hour back

JavaDate

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

java.util.Calendar

Calendar cal = Calendar.getInstance();
// remove next line if you're always using the current time.
cal.setTime(currentDate);
cal.add(Calendar.HOUR, -1);
Date oneHourBack = cal.getTime();

java.util.Date

new Date(System.currentTimeMillis() - 3600 * 1000);

org.joda.time.LocalDateTime

new LocalDateTime().minusHours(1)

Java 8: java.time.LocalDateTime

LocalDateTime.now().minusHours(1)

Java 8 java.time.Instant

// always in UTC if not timezone set
Instant.now().minus(1, ChronoUnit.HOURS));
// with timezone, Europe/Berlin for example
Instant.now()
	   .atZone(ZoneId.of("Europe/Berlin"))
	   .minusHours(1));

Solution 2 - Java

Similar to @Sumit Jain's solution

Date currentDate = new Date(System.currentTimeMillis() - 3600 * 1000);

or

Date currentDate = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1));

Solution 3 - Java

tl;dr

In UTC:

Instant.now().minus( 1 , ChronoUnit.HOURS ) 

Or, zoned:

Instant.now()
       .atZone( ZoneId.of ( "America/Montreal" ) )
       .minusHours( 1 )

Using java.time

Java 8 and later has the new java.time framework built-in.

Instant

If you only care about UTC (GMT), then use the Instant class.

Instant instant = Instant.now ();
Instant instantHourEarlier = instant.minus ( 1 , ChronoUnit.HOURS );

Dump to console.

System.out.println ( "instant: " + instant + " | instantHourEarlier: " + instantHourEarlier );

>instant: 2015-10-29T00:37:48.921Z | instantHourEarlier: 2015-10-28T23:37:48.921Z

Note how in this instant happened to skip back to yesterday’s date.

ZonedDateTime

If you care about a time zone, use the ZonedDateTime class. You can start with an Instant and the assign a time zone, a ZoneId object. This class handles the necessary adjustments for anomalies such as Daylight Saving Time (DST).

Instant instant = Instant.now ();
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
ZonedDateTime zdtHourEarlier = zdt.minus ( 1 , ChronoUnit.HOURS );

Dump to console.

System.out.println ( "instant: " + instant + "\nzdt: " + zdt + "\nzdtHourEarlier: " + zdtHourEarlier );

>instant: 2015-10-29T00:50:30.778Z

>zdt: 2015-10-28T20:50:30.778-04:00[America/Montreal]

>zdtHourEarlier: 2015-10-28T19:50:30.778-04:00[America/Montreal]

Conversion

The old java.util.Date/.Calendar classes are now outmoded. Avoid them. They are notoriously troublesome and confusing.

When you must use the old classes for operating with old code not yet updated for the java.time types, call the conversion methods. Here is example code going from an Instant or a ZonedDateTime to a java.util.Date.

java.util.Date date = java.util.Date.from( instant );

…or…

java.util.Date date = java.util.Date.from( zdt.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Solution 4 - Java

Use Calendar.

Calendar cal = Calendar.getInstance();

cal.setTime(new Date());
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) - 1);

Solution 5 - Java

Or using the famous Joda Time library:

DateTime dateTime = new DateTime();
dateTime = dateTime.minusHours(1);
Date modifiedDate = dateTime.toDate();

Solution 6 - Java

Just subtract the number of milliseconds in an hour from the date.

currentDate.setTime(currentDate.getTime() - 3600 * 1000));

Solution 7 - Java

You can use from bellow code for date and time :

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	   //get current date time with Calendar()
	   Calendar cal = Calendar.getInstance();
	   System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));

	   cal.add(Calendar.DATE, 1);
	   System.out.println("Add one day to current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.MONTH, 1);
	   System.out.println("Add one month to current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.YEAR, 1);
	   System.out.println("Add one year to current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.HOUR, 1);
	   System.out.println("Add one hour to current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.MINUTE, 1);
	   System.out.println("Add one minute to current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.SECOND, 1);
	   System.out.println("Add one second to current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.DATE, -1);
	   System.out.println("Subtract one day from current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.MONTH, -1);
	   System.out.println("Subtract one month from current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.YEAR, -1);
	   System.out.println("Subtract one year from current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.HOUR, -1);
	   System.out.println("Subtract one hour from current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.MINUTE, -1);
	   System.out.println("Subtract one minute from current date : " + dateFormat.format(cal.getTime()));

	   cal = Calendar.getInstance();
	   cal.add(Calendar.SECOND, -1);
	   System.out.println("Subtract one second from current date : " + dateFormat.format(cal.getTime()));

Output :

Current Date Time : 2008/12/28 10:24:53
Add one day to current date : 2008/12/29 10:24:53
Add one month to current date : 2009/01/28 10:24:53
Add one year to current date : 2009/12/28 10:24:53
Add one hour to current date : 2008/12/28 11:24:53
Add one minute to current date : 2008/12/28 10:25:53
Add one second to current date : 2008/12/28 10:24:54
Subtract one day from current date : 2008/12/27 10:24:53
Subtract one month from current date : 2008/11/28 10:24:53
Subtract one year from current date : 2007/12/28 10:24:53
Subtract one hour from current date : 2008/12/28 09:24:53
Subtract one minute from current date : 2008/12/28 10:23:53
Subtract one second from current date : 2008/12/28 10:24:52

This link is good : See here

And see : See too

And : Here

And : Here

And : Here

If you need just time :

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

Solution 8 - Java

This can be achieved using java.util.Date. The following code will subtract 1 hour from your date.

Date date = new Date(yourdate in date format);
Date newDate = DateUtils.addHours(date, -1)

Similarly for subtracting 20 seconds from your date

newDate = DateUtils.addSeconds(date, -20)    

Solution 9 - Java

To subtract hours, you need to use the HOUR_OF_DAY constant. Within that, include the number with the negative sign. This would be the hours you want to reduce. All this is done under the Calendar add() method.

The following is an example:

import java.util.Calendar;
public class Example {
  public static void main(String[] args) {
   Calendar c = Calendar.getInstance();
     System.out.println("Date : " + c.getTime());
       // 2 hours subtracted
   c.add(Calendar.HOUR_OF_DAY, -2);
   System.out.println("After subtracting 2 hrs : " + c.getTime());
 }
}

Here is the output:

Date : Sun Dec 16 16:28:53 UTC 2018
After subtracting 2 hrs : Sun Dec 16 14:28:53 UTC 2018

Solution 10 - Java

Get the time in milliseconds, minus your minutes in milliseconds and convert it to Date. Here you need to objectify one!!!

    int minutes = 60;
    long currentDateTime = System.currentTimeMillis();
    Date currentDate = new Date(currentDateTime - minutes*60*1000);
    System.out.println(currentDate);

Solution 11 - Java

It worked for me instead using format .To work with time just use parse and toString() methods

String localTime="6:11"; LocalTime localTime = LocalTime.parse(localtime)

LocalTime lt = 6:11; localTime = lt.toString()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMakkyView Question on Stackoverflow
Solution 1 - JavaKimiView Answer on Stackoverflow
Solution 2 - JavaPeter LawreyView Answer on Stackoverflow
Solution 3 - JavaBasil BourqueView Answer on Stackoverflow
Solution 4 - JavaadarshrView Answer on Stackoverflow
Solution 5 - JavaJean LogeartView Answer on Stackoverflow
Solution 6 - JavaSumit JainView Answer on Stackoverflow
Solution 7 - Javauser4813855View Answer on Stackoverflow
Solution 8 - JavaDhananjayView Answer on Stackoverflow
Solution 9 - Javanarcis dprView Answer on Stackoverflow
Solution 10 - JavaZenithView Answer on Stackoverflow
Solution 11 - JavaShahid Hussain AbbasiView Answer on Stackoverflow