- Add or Subtract Hours, Minutes and Seconds in Java
- How To Minus Minutes From LocalDateTime In Java
- How to subtract minutes from the current local date-time in Java
- Subtract minutes from date
- Straight up Java
- Java 8 Date and Time API
- Joda Time
- Apache Commons
- Java Add/subtract years, months, days, hours, minutes, or seconds to a Date & Time
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 Minus Minutes From LocalDateTime In Java
To subtract minutes from the local date-time, Java provides a class i.e. LocalDateTime, and a method i.e. minusMinutes() method.
In this article, we are going to subtract minutes from local date-time with several running examples.
/* * Code example to minus minutes from 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 string date into date time LocalDateTime date = LocalDateTime.parse(strDate); // Displaying date and time System.out.println("Date : "+date); // Minus 1 minute to the date LocalDateTime newDate = date.minusMinutes(1); // Display result System.out.println("New Date : "+newDate); >>
Date : 2022-03-14T17:28:13.048999208
New Date : 2022-03-14T17:27:13.048999208
The subtracted minutes are highlighted in black in the output
Here, we first get parsed the String date to the LocalDateTime object by using the parse() method.
If you already have locadatetime object, then you don’t need to parse it.
You can directly call the minusMinutes() method.
Now, let’s have a look at this method signature:
public LocalDateTime minusMinutes(long minutes)
Package Name: java.time;
Return Value: It returns a copy of localdatetime after subtracting the specified number of minutes, 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.
Version: Since 1.8
How to subtract minutes from the current local date-time in Java
If you wish to subtract minutes from the current local date-time in Java, then use the below code.
Here, we used the now() method to get the current date-time and then used the minusMinutes() method. See the below code.
/* * Code example to minus minutes from date and time in Java */ import java.time.LocalDateTime; public class JExercise < public static void main(String[] args) < // current date time LocalDateTime date = LocalDateTime.now(); // Displaying date and time System.out.println("Date : "+date); // Minus 1 minute to the date LocalDateTime newDate = date.minusMinutes(1); // Display result System.out.println("New Date : "+newDate); >>
Date : 2022-03-14T20:40:53.801755847
New Date : 2022-03-14T20:39:53.801755847
The minusMinutes() method accepts negative arguments as well.
If we pass the minutes as negative values then it does the reversal operation and adds the minutes rather than subtracting. See the code below.
/* * Code example to minus minutes from date and time in Java */ import java.time.LocalDateTime; public class JExercise < public static void main(String[] args) < // current date time LocalDateTime date = LocalDateTime.now(); // Displaying date and time System.out.println("Date : "+date); // Minus 1 minute to the date LocalDateTime newDate = date.minusMinutes(-1); // Display result System.out.println("New Date : "+newDate); >>
Date : 2022-03-14T20:43:05.023837456
New Date : 2022-03-14T20:44:05.023837456
Subtract minutes from date
Opposite of adding minutes to a java date, this example shows how to subtract minutes from a date using java’s Calendar.add, java 8 date time api, joda’s DateTime.minusMinutes and apache commons DateUtils.addMinutes. In each of the examples below, we will set a date that represents new years day or January 1st. Then we will subtract 1 minute to return a date that reperesents new years eve or December 31st.
Straight up Java
@Test public void subtract_minutes_from_date_in_java () Calendar newYearsDay = Calendar.getInstance(); newYearsDay.set(2013, 0, 1, 0, 0, 0); Calendar newYearsEve = Calendar.getInstance(); newYearsEve.setTimeInMillis(newYearsDay.getTimeInMillis()); newYearsEve.add(Calendar.MINUTE, -1); SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); logger.info(dateFormatter.format(newYearsDay.getTime())); logger.info(dateFormatter.format(newYearsEve.getTime())); assertTrue(newYearsEve.before(newYearsDay)); >
01/01/2013 00:00:00 CST 12/31/2012 23:59:00 CST
Java 8 Date and Time API
Java 8 LocalDateTime.minusMinutes will return a copy of the LocalDateTime with the specified number of minutes subtracted.
@Test public void subtract_minutes_from_date_in_java8 () LocalDateTime newYearsDay = LocalDateTime.of(2013, Month.JANUARY, 1, 0, 0); LocalDateTime newYearsEve = newYearsDay.minusMinutes(1); java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss S"); logger.info(newYearsDay.format(formatter)); logger.info(newYearsEve.format(formatter)); assertTrue(newYearsEve.isBefore(newYearsDay)); >
01/01/2013 00:00:00 CST 12/31/2012 23:59:00 CST
Joda Time
Joda DateTime.minusMinutes will return a copy the DateTime minus the specified number of minutes.
@Test public void subtract_minutes_from_date_in_java_with_joda () DateTime newYearsDay = new DateTime(2013, 1, 1, 0, 0, 0, 0); DateTime newYearsEve = newYearsDay.minusMinutes(1); DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z"); logger.info(newYearsDay.toString(fmt)); logger.info(newYearsEve.toString(fmt)); assertTrue(newYearsEve.isBefore(newYearsDay)); >
01/01/2013 00:00:00 CST 12/31/2012 23:59:00 CST
Apache Commons
Apache commons DateUtils.addMinutes will adds a number of minutes, in this case a negative number of minutes, to the date returning a new object.
@Test public void subtract_minutes_from_date_in_java_apachecommons () Calendar newYearsDay = Calendar.getInstance(); newYearsDay.set(2013, 0, 1, 0, 0, 0); Date newYearsEve = DateUtils.addMinutes(newYearsDay.getTime(), -1); SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); logger.info(dateFormatter.format(newYearsDay.getTime())); logger.info(dateFormatter.format(newYearsEve)); assertTrue(newYearsEve.before(newYearsDay.getTime())); >
01/01/2013 00:00:00 CST 12/31/2012 23:59:00 CST
Subtract minutes from date posted by Justin Musgrove on 04 February 2014
Tagged: java, java-date, and java-date-math
Java Add/subtract years, months, days, hours, minutes, or seconds to a Date & Time
In this article, you’ll find several ways of adding or subtracting years, months, days, hours, minutes, or seconds to a Date in Java.
Add/Subtract years, months, days, hours, minutes, seconds to a Date using Calendar class
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class CalendarAddSubtractExample public static void main(String[] args) SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); System.out.println("Current Date " + dateFormat.format(date)); // Convert Date to Calendar Calendar c = Calendar.getInstance(); c.setTime(date); // Perform addition/subtraction c.add(Calendar.YEAR, 2); c.add(Calendar.MONTH, 1); c.add(Calendar.DATE, -10); c.add(Calendar.HOUR, -4); c.add(Calendar.MINUTE, 30); c.add(Calendar.SECOND, 50); // Convert calendar back to Date Date currentDatePlusOne = c.getTime(); System.out.println("Updated Date " + dateFormat.format(currentDatePlusOne)); > >
# Output Current Date 2020-02-24 19:35:00 Updated Date 2022-03-14 16:05:50
Add/Subtract years, months, weeks, days, hours, minutes, seconds to LocalDateTime
import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class LocalDateTimeAddSubtractExample public static void main(String[] args) LocalDateTime dateTime = LocalDateTime.of(2020, 1, 26, 10, 30, 45); // Add years, months, weeks, days, hours, minutes, seconds to LocalDateTime LocalDateTime newDateTime = dateTime.plusYears(3).plusMonths(1).plusWeeks(4).plusDays(2).plusHours(2); System.out.println(newDateTime); // Subtract years, months, weeks, days, hours, minutes, seconds to LocalDateTime newDateTime = dateTime.minusYears(3).minusMonths(1).minusWeeks(4).minusDays(2).minusMinutes(30); System.out.println(newDateTime); // Add/Subtract using the generic plus/minus method System.out.println(dateTime.plus(2, ChronoUnit.DAYS)); > >
# Output 2023-03-28T12:30:45 2016-11-26T10:00:45 2020-01-28T10:30:45
Add/Subtract days, weeks, months, years to LocalDate
import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class LocalDateAddSubtractExample public static void main(String[] args) LocalDate date = LocalDate.of(2020, 1, 26); // Add years, months, weeks, days to LocalDate LocalDate newDate = date.plusYears(3).plusMonths(1).plusWeeks(4).plusDays(2); System.out.println(newDate); // Subtract years, months, weeks, days to LocalDate newDate = date.minusYears(3).minusMonths(1).minusWeeks(4).minusDays(2); System.out.println(newDate); // Add/Subtract using the generic plus/minus method System.out.println(date.plus(2, ChronoUnit.DAYS)); > >
2023-03-28 2016-11-26 2020-01-28
Add/Subtract hours, minutes, seconds to LocalTime
import java.time.LocalTime; import java.time.temporal.ChronoUnit; public class LocalTimeAddSubtractExample public static void main(String[] args) LocalTime time = LocalTime.of(11, 45, 20); // Add hours, minutes, or seconds LocalTime newTime = time.plusHours(2).plusMinutes(30).plusSeconds(80); System.out.println(newTime); // Subtract hours, minutes, or seconds LocalTime updatedTime = time.minusHours(2).minusMinutes(30).minusSeconds(30); System.out.println(updatedTime); // Add/Subtract using the generic plus/minus method System.out.println(time.plus(1, ChronoUnit.HOURS)); > >
# Output 14:16:40 09:14:50 12:45:20