Java add one hour to date

Add hours to date

Opposite of subtracting hours from a java date, this example will demonstrates how to add hours to date using Calendar.add, java 8 date time api, joda LocalDateTime.plusHours and apache commons DateUtils.addHours. In the examples below, we will set a date that represents new years eve, December 31st, then adding one hour to return a date representing new years day or January 1st.

Straight up Java

@Test public void add_hours_to_date_in_java ()  Calendar newYearsEve = Calendar.getInstance(); newYearsEve.set(2012, 11, 31, 23, 0, 0); Calendar newYearsDay = Calendar.getInstance(); newYearsDay.setTimeInMillis(newYearsEve.getTimeInMillis()); newYearsDay.add(Calendar.HOUR, 1); SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); logger.info(dateFormatter.format(newYearsEve.getTime())); logger.info(dateFormatter.format(newYearsDay.getTime())); assertTrue(newYearsDay.after(newYearsEve)); >
12/31/2012 23:00:00 CST 01/01/2013 00:00:00 CST

Java 8 Date and Time API

Java 8 LocalDateTime.plusHours will return a copy of the LocalDateTime with the specified number of hours added.

@Test public void add_hours_to_date_in_java8()  LocalDateTime newYearsEve = LocalDateTime.of(2012, Month.DECEMBER, 31, 23, 0); LocalDateTime newYearsDay = newYearsEve.plusHours(1); java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter .ofPattern("MM/dd/yyyy HH:mm:ss S"); logger.info(newYearsEve.format(formatter)); logger.info(newYearsDay.format(formatter)); assertTrue(newYearsDay.isAfter(newYearsEve)); >
12/31/2012 23:00:00 0 01/01/2013 00:00:00 0

Joda Time

Joda DateTime.plusHours will return a copy the DateTime plus the specified number of hours.

@Test public void add_hours_to_date_in_java_with_joda ()  DateTime newYearsEve = new DateTime(2012, 12, 31, 23, 0, 0, 0); DateTime newYearsDay = newYearsEve.plusHours(1); DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z"); logger.info(newYearsEve.toString(fmt)); logger.info(newYearsDay.toString(fmt)); assertTrue(newYearsDay.isAfter(newYearsEve)); >
12/31/2012 23:00:00 CST 01/01/2013 00:00:00 CST

Apache Commons

Apache commons DateUtils.addHours will add a number of hours to the date returning a new object.

@Test public void add_hours_to_date_in_java_with_apachecommons ()  Calendar newYearsEve = Calendar.getInstance(); newYearsEve.set(2012, 11, 31, 23, 0, 0); Date newYearsDay = DateUtils.addHours(newYearsEve.getTime(), 1); SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); logger.info(dateFormatter.format(newYearsEve.getTime())); logger.info(dateFormatter.format(newYearsDay)); assertTrue(newYearsDay.after(newYearsEve.getTime())); >
12/31/2012 23:00:00 CST 01/01/2013 00:00:00 CST

Add hours to date posted by Justin Musgrove on 04 February 2014

Tagged: java, java-date, and java-date-math

Источник

How to add hours to LocalDateTime in Java?

To add hours to time in Java, you can use plusHours() method of the LocalDateTime class in Java.

This article introduces how to add hours to localdatetime in Java.

We will add hours to a string date and current date as well. Let’s see the running examples.

Adding hours to localdatetime in Java

If you have a date in String then first parse it using the parse() method to get the localdatetime object.

After that use the plusHours() method to add hours to it.

/* * Code example to add hours to date and time in Java */ import java.time.LocalDateTime; public class JExercise < public static void main(String[] args) < // String date is given String strDate = "2022-03-14T17:28:13.048999208"; // parse the date into date time LocalDateTime date = LocalDateTime.parse(strDate); // Displaying date and time System.out.println("Date : "+date); // Add 2 hours to the date LocalDateTime newDate = date.plusHours(2); // Display result System.out.println("New Date : "+newDate); >>

Date : 2022-03-14T17:28:13.048999208
New Date : 2022-03-14T19:28:13.048999208

If you already have localdatetime object then no need to use the parse() method, just use the plusHours() method directly.

Syntax

The signature of the plusHours() method is as below.

public LocalDateTime plusHours(long hours) 

Package Name: java.time;

Class Name: LocalDateTime

Return Value: It returns a copy of localdatetime after adding the specified number of hours, not null.

Parameters: It takes a single long type value. It may be negative.

Exceptions: It throws a DateTimeException if the result exceeds the supported(either MIN or MAX) date range.

This original instance(localdatetime) is immutable and unaffected by this method call.

The LocalDateTime is a class that represents local date and time in Java.

This class consists of year, month, date, hour, minute, second, and nanoseconds. See the below datetime formation.

localdatetime format in java

Adding hours to the current date and time in Java

Here, we used the static now() method of LocalDateTime class to get the current date and time.

After that, we used the plusHours() to add hours to this date.

/* * Code example to add hours to date and time in Java */ import java.time.LocalDateTime; public class JExercise < public static void main(String[] args) < // Current date and time LocalDateTime date = LocalDateTime.now(); // Displaying date and time System.out.println("Date : "+date); // Add 2 hours to the date LocalDateTime newDate = date.plusHours(2); // Display result System.out.println("New Date : "+newDate); >>

Date : 2022-03-14T18:18:18.704649698
New Date : 2022-03-14T20:18:18.704649698

Subtract Hours from Time in Java

The plusHours() method allows negative value as well. So if we passed a negative number then it subtract the hours from the date.

So we can say that if we pass a negative value then it subtracts the hours rather than adding to the date. See the code example below.

/* * Code example to add hours to date and time in Java */ import java.time.LocalDateTime; public class JExercise < public static void main(String[] args) < // String date is given String strDate = "2022-03-14T17:28:13.048999208"; // parse the date into date time LocalDateTime date = LocalDateTime.parse(strDate); // Displaying date and time System.out.println("Date : "+date); // Add 2 hours to the date LocalDateTime newDate = date.plusHours(-2); // Display result System.out.println("New Date : "+newDate); >>

Date : 2022-03-14T17:28:13.048999208
New Date : 2022-03-14T15:28:13.048999208

Источник

Add or Subtract Hours, Minutes and Seconds in Java

Learn to add or subtract hours, minutes or seconds from a given date and time in Java using various date-time classes. If we require adding or subtracting the days and months, read the linked article.

1. Add or Subtract Time Since Java 8

Using the new Date API is the recommended approach if we use JDK 1.8 or later.

The following classes are part of the new API that can store and manipulate the time information for a given date.

The Duration class represents the amount of time in seconds and nanoseconds, and accessed using other duration-based units, such as minutes and hours. We can add or subtract a Duration from any class above.

1.2. Adding Hours, Minutes and Seconds

The LocalDateTime, ZoneDateTime and OffsetDateTime classes are an immutable representation of a date-time to a precision of nanoseconds. These classes support the plus methods to add the time to the date.

  • plusHours(n) : returns a copy of given date-time object with the ‘n’ hours added.
  • plusMinutes(n) : returns a copy of given date-time object with the ‘n’ minutes added.
  • plusSeconds(n) : returns a copy of given date-time object with the ‘n’ seconds added.
  • plusNanos(n) : returns a copy of given date-time object with the ‘n’ nano-seconds added.
  • plus(duration) : returns a copy of given date-time object with the specified Duration added.
  • plus(n, temporalUnit) : returns a copy of given date-time object with ‘n’ amount of specified unit added.

Java program to add hours and other time units to a given date-time. We are writing the examples using the LocalDateTime class, but all the statements are valid for ZoneDateTime and OffsetDateTime classes.

LocalDateTime updatedTime LocalDateTime now = LocalDateTime.now(); updatedTime = now.plusHours(2); updatedTime = now.plusMinutes(20); updatedTime = now.plusSeconds(300); updatedTime = now.plus(Duration.ofMillis(8000)); updatedTime = now.plus(20, ChronoUnit.HOURS);

The Instant class is meant to be representing a date. It is for representing a single instantaneous point on the timeline or epoch-seconds. It does not provide plusHours and plusMinutes methods.

 Instant updatedInstant; Instant currentInstant = Instant.parse("2022-06-24T05:12:35Z"); updatedInstant = currentInstant.plus(2, ChronoUnit.HOURS); updatedInstant = currentInstant.plus(30, ChronoUnit.MINUTES); updatedInstant = currentInstant.plusSeconds(300); updatedInstant = currentInstant.plusMillis(8000 updatedInstant = currentInstant.plusNanos(60000

1.3. Subtracting Hours, Minutes and Seconds

Similar to plus methods, these classes provide a way to subtract any amount of time. We need to use the minus methods listed above.

LocalDateTime updatedTime LocalDateTime now = LocalDateTime.now(); updatedTime = now.minusHours(2); updatedTime = now.minusMinutes(20); updatedTime = now.minusSeconds(300); updatedTime = now.minus(Duration.ofMillis(8000)); updatedTime = now.minus(20, ChronoUnit.HOURS);

Similarly, for the Instant class we can use the minus methods.

Instant updatedInstant; Instant currentInstant = Instant.parse("2022-06-24T05:12:35Z"); updatedInstant = currentInstant.minus(2, ChronoUnit.HOURS); updatedInstant = currentInstant.minus(30, ChronoUnit.MINUTES); updatedInstant = currentInstant.minusSeconds(300); updatedInstant = currentInstant.minusMillis(8000 updatedInstant = currentInstant.minusNanos(600000);

2. Add or Subtract Time – Java 7

Adding and subtracting time was possible through the Calendar class. There was no direct support in the Date class.

We can use the cal.add(unit, amount) method for adding and subtracting time.

  • If the amount was positive number then specified amount of specified unit of time is added to the calendar.
  • If the amount was negative number then specified amount of specified unit of time is subtracted from the calendar.
Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.HOUR, 2); cal.add(Calendar.MINUTE, -15); cal.add(Calendar.SECOND, 10);

Note that Calendar is a mutable object so all changes are made to the given Calendar instance itself. No new Calendar instance is created.

In this tutorial, we learned to add and subtract the time (in hours, minutes and seconds) to a date in Java. We learned to use the new Java Date APIs as well as the old legacy Date and Calendar classes.

Источник

How to add hours to LocalDateTime in Java?

To add hours to time in Java, you can use plusHours() method of the LocalDateTime class in Java.

This article introduces how to add hours to localdatetime in Java.

We will add hours to a string date and current date as well. Let’s see the running examples.

Adding hours to localdatetime in Java

If you have a date in String then first parse it using the parse() method to get the localdatetime object.

After that use the plusHours() method to add hours to it.

/* * Code example to add hours to date and time in Java */ import java.time.LocalDateTime; public class JExercise < public static void main(String[] args) < // String date is given String strDate = "2022-03-14T17:28:13.048999208"; // parse the date into date time LocalDateTime date = LocalDateTime.parse(strDate); // Displaying date and time System.out.println("Date : "+date); // Add 2 hours to the date LocalDateTime newDate = date.plusHours(2); // Display result System.out.println("New Date : "+newDate); >>

Date : 2022-03-14T17:28:13.048999208
New Date : 2022-03-14T19:28:13.048999208

If you already have localdatetime object then no need to use the parse() method, just use the plusHours() method directly.

Syntax

The signature of the plusHours() method is as below.

public LocalDateTime plusHours(long hours) 

Package Name: java.time;

Class Name: LocalDateTime

Return Value: It returns a copy of localdatetime after adding the specified number of hours, not null.

Parameters: It takes a single long type value. It may be negative.

Exceptions: It throws a DateTimeException if the result exceeds the supported(either MIN or MAX) date range.

This original instance(localdatetime) is immutable and unaffected by this method call.

The LocalDateTime is a class that represents local date and time in Java.

This class consists of year, month, date, hour, minute, second, and nanoseconds. See the below datetime formation.

localdatetime format in java

Adding hours to the current date and time in Java

Here, we used the static now() method of LocalDateTime class to get the current date and time.

After that, we used the plusHours() to add hours to this date.

/* * Code example to add hours to date and time in Java */ import java.time.LocalDateTime; public class JExercise < public static void main(String[] args) < // Current date and time LocalDateTime date = LocalDateTime.now(); // Displaying date and time System.out.println("Date : "+date); // Add 2 hours to the date LocalDateTime newDate = date.plusHours(2); // Display result System.out.println("New Date : "+newDate); >>

Date : 2022-03-14T18:18:18.704649698
New Date : 2022-03-14T20:18:18.704649698

Subtract Hours from Time in Java

The plusHours() method allows negative value as well. So if we passed a negative number then it subtract the hours from the date.

So we can say that if we pass a negative value then it subtracts the hours rather than adding to the date. See the code example below.

/* * Code example to add hours to date and time in Java */ import java.time.LocalDateTime; public class JExercise < public static void main(String[] args) < // String date is given String strDate = "2022-03-14T17:28:13.048999208"; // parse the date into date time LocalDateTime date = LocalDateTime.parse(strDate); // Displaying date and time System.out.println("Date : "+date); // Add 2 hours to the date LocalDateTime newDate = date.plusHours(-2); // Display result System.out.println("New Date : "+newDate); >>

Date : 2022-03-14T17:28:13.048999208
New Date : 2022-03-14T15:28:13.048999208

Источник

Читайте также:  Javascript методы работы с массивом
Оцените статью