- We have already seen how to subtract number of days from java using calendar and using java 8.
- How to subtract X days from a date using Java calendar and with java 8
- Now we will discuss here how to subtract hours from java 8 localdatetime.
- Some times we will get out date time in string format so we will convert our string format date to java 8 LocaDateTime object.
- We can user DateTimeFormatter to tell the format of date time to LocalDateTime class.
- LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
- LocalDateTime has minusHours(numberOfHours) method to subtract hours from date time.
- Lets see an example java program to subtract hours from java date time using java 8 LocalDateTime class.
- How to subtract hours from java 8 date time.
Program #1 : Java Example Program to subtract hours from given string formatted date time using java 8.
- package java8;
- /**
- * By: www.instanceofjava.com
- * program: how to subtract hours from date time using java 8
- *
- */
- import java.time.LocalDateTime;
- import java.time.format.DateTimeFormatter;
- public class SubstractHoursJava{
- public static void main(String[] args) {
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
- String currentTime= "2017-10-19 22:00:00";
- System.out.println("Before subtraction of hours from date: "+currentTime);
- LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
- datetime=datetime.minusHours(4);
- String aftersubtraction=datetime.format(formatter);
- System.out.println("After 4 hours subtraction from date: "+aftersubtraction);
- }
- }
Output:
- Before subtraction of hours from date: 2017-10-19 22:00:00
- After 4 hours subtraction from date: 2017-10-19 18:00:00
- Now we will see how to subtract one hour from current date time in java using java 8
Program #2 : Java Example Program to subtract one hour from given current date time using java 8.
- package java8;
- /**
- * By: www.instanceofjava.com
- * program: how to subtract hours from date time using java 8
- *
- */
- import java.time.LocalDateTime;
- import java.time.format.DateTimeFormatter;
- public class SubtractOneHour {
- public static void main(String[] args) {
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd H:mm:ss");
- LocalDateTime datetime = LocalDateTime.now();
- System.out.println("Before subtraction of hours from date: "+datetime.format(formatter));
- datetime=datetime.minusHours(1);
- String aftersubtraction=datetime.format(formatter);
- System.out.println("After 1 hour subtraction from date: "+aftersubtraction);
- }
- }
- Before subtraction of hours from date: 2017-10-19 23:14:12
- After 1 hour subtraction from date: 2017-10-19 22:14:12
No comments