In Java 8, java.time.LocalDateTime class is used to perform manipulation on the date value. Class itself has 2 methods to subtract the hours from the date:
1) minusMinutes - Takes an integer. Date will be reduced by given number of minutes
2) minus - Takes an argument of class Duration
Both these methods returns copy of LocalDateTime object.
This time we will use the (to) factory of LocalDateTime and pass the custom parameters. Let’s say your cake should be ready by half an hour. All the core classes in the new API are constructed by fluent factory methods. When constructing a value by its constituent fields, the factory is called of;
In the below example, Date is initialized to 5th DECEMBER 2014. 30 minutes are deducted using both the methods.
import java.time.Duration; import java.time.LocalDateTime; import java.time.Month; public class SubtractMinutesFromDate { static java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter .ofPattern("dd-MMM-yyyy HH:mm:ss"); public static void subMinutesFromDate_withMinusMinutes() { // Date is initialized to 5th DECEMBER 2014 LocalDateTime birthday = LocalDateTime.of(2014, Month.DECEMBER, 5, 0, 0); LocalDateTime birthdayParty = birthday.minusMinutes(30); System.out.println("Birthday Bash : \t" + birthday.format(formatter)); System.out.println("But cake should be ready by : \t" + birthdayParty.format(formatter)); } public static void subMinutesFromDate_usingMinusDurationofMins() { // Date is initialized to 5th Dec 2014 LocalDateTime birthday = LocalDateTime.of(2014, Month.DECEMBER, 5, 0, 0); LocalDateTime birthdayParty = birthday.minus(Duration.ofMinutes(30)); System.out.println("Birthday Bash : \t" + birthday.format(formatter)); System.out.println("But cake should be ready by (using Duration) : \t" + birthdayParty.format(formatter)); } public static void main(String[] args) { subMinutesFromDate_withMinusMinutes(); subMinutesFromDate_usingMinusDurationofMins(); } }
Output :
Birthday Bash : 05-Dec-2014 00:00:00 But cake should be ready by : 04-Dec-2014 23:30:00 Birthday Bash : 05-Dec-2014 00:00:00 But cake should be ready by (using Duration) : 04-Dec-2014 23:30:00
This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.
No comments:
Post a Comment