Java 8 Date Utility Class

In this article, we will discuss a few commonly used Java 8 Date Time utility methods. We can also show you the sample JUnit test cases for all Java 8 Date Utility methods.

Java 8 Date Utility Class contains the date and time-related utility methods that you can use in your day-to-day project work.

Don't forget to checkout productive our Java 8 Date Time API Tutorial

Java8DateUtility Class Methods

  • getLocalDateFromClock() - Get current local date.
  • LocalDate getNextDay(LocalDate localDate) - Get next day.
  • LocalDate getNextDay(LocalDate localDate) - Get next day.
  • LocalDate getPreviousDay(LocalDate localDate) - Get Previous Day.
  • DayOfWeek getDayOfWeek(LocalDate localDate) - Get day of the week.
  • LocalDate getFirstDayOfMonth() - Get first day of the Month.
  • LocalDateTime getStartOfDay(LocalDate localDate) - Get start of the Day.
  • printCurrentDayMonthAndYear() - Print current time in day,month and year format.
  • checkDateEquals(LocalDate date, LocalDate today) - Check two dates are equals.
  • LocalTime getCurrentTime() - Get current time.
  • LocalTime addHoursToTime(int hours) - Add hours to time.
  • ZonedDateTime timeZone(String timeZone) - Get date and time by zone.
  • checkLeafYear() - Check for leaf year.
  • Instant getTimeStamp() - get time stamp.
  • LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) - Get Date by hour,minute and seconds.
  • ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) - Get zone date time.
  • LocalTime modifyDates(LocalTime localTime, Duration duration) - Returns a copy of this time with the specified amount added.
  • Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) - Obtains a Duration representing the duration between two temporal objects.
  • LocalDateTime getLocalDateTimeUsingParseMethod(String representation) - Get date and time by passing format.
  • LocalDateTime convertDateToLocalDate(Date date) - Convert Date to Java 8 LocalDate.
  • LocalDateTime convertDateToLocalDate(Calendar calendar) - Convert Calendar to LocalDate

Java8DateUtility.java

package com.ramesh.java8.datetime;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;

/**
 * Useful Java8DateUtiliy Methods
 * @author javaguides.net
 *
 */

public final class Java8DateUtility {

 /**
  *  Get current local date.
  * @return
  */
 public static LocalDate getLocalDateFromClock() {
     return LocalDate.now();
 }

 /**
  * Get next day.
  * @param localDate
  * @return
  */
 public static LocalDate getNextDay(LocalDate localDate) {
     return localDate.plusDays(1);
 }

 /**
  * Get Previous Day.
  * @param localDate
  * @return
  */
 public static LocalDate getPreviousDay(LocalDate localDate) {
     return localDate.minus(1, ChronoUnit.DAYS);
 }

 /**
  * Get day of the week.
  * @param localDate
  * @return
  */
 public static DayOfWeek getDayOfWeek(LocalDate localDate) {
     DayOfWeek day = localDate.getDayOfWeek();
     return day;
 }

 /**
  * Get first day of the Month.
  * @return LocalDate
  */
 public static LocalDate getFirstDayOfMonth() {
     LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
     return firstDayOfMonth;
 }

 /**
  * Get start of the Day.
  * @param localDate
  * @return
  */
 public static LocalDateTime getStartOfDay(LocalDate localDate) {
     LocalDateTime startofDay = localDate.atStartOfDay();
     return startofDay;
 }

 /**
  * Print current time in day,month and year format.
  */
 public static void printCurrentDayMonthAndYear() {
     LocalDate today = LocalDate.now();
     int year = today.getYear();
     int month = today.getMonthValue();
     int day = today.getDayOfMonth();
     System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day);
 }

 /**
  * Check two dates are equals.
  * @param date
  * @param today
  * @return
  */
 public static boolean checkDateEquals(LocalDate date, LocalDate today) {
     if (date.equals(today)) {
        System.out.printf("Today %s and date1 %s are same date %n", today, date);
        return true;
     }
     return false;
 }

 /**
  * Get current time.
  * @return
  */
 public static LocalTime getCurrentTime() {
     LocalTime time = LocalTime.now();
     System.out.println("local time now : " + time);
     return time;
 }

 /**
  * Add hours to time.
  * @param hours
  * @return
  */
 public static LocalTime addHoursToTime(int hours) {
     LocalTime time = LocalTime.now();
     LocalTime newTime = time.plusHours(hours); // adding two hours
     System.out.println("Time after 2 hours : " + newTime);
     return newTime;
 }

 /**
  * Get date and time by zone.
  * @param timeZone
  * @return
  */
 public static ZonedDateTime timeZone(String timeZone) {
     ZoneId america = ZoneId.of(timeZone);
     LocalDateTime localtDateAndTime = LocalDateTime.now();
     ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america);
     System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork);
     return dateAndTimeInNewYork;
 }

 /**
  * Check for leap year.
  */
 public static void checkLeapYear() {
     LocalDate today = LocalDate.now();
     if (today.isLeapYear()) {
         System.out.println("This year is Leap year");
     } else {
         System.out.println("2014 is not a Leap year");
     }
 }

 /**
  * get time stamp.
  * @return
  */
 public static Instant getTimeStamp() {
     Instant timestamp = Instant.now();
     System.out.println("What is value of this instant " + timestamp);
     return timestamp;
 }

 /**
  * Get Date by hour,minute and seconds.
  * @param hour
  * @param min
  * @param seconds
  * @return
  */
 public static LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
      return LocalTime.of(hour, min, seconds);
 }

 /**
  * Get zone date time.
  * @param localDateTime
  * @param zoneId
  * @return
  */
 public static ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
      return ZonedDateTime.of(localDateTime, zoneId);
 }

 /**
  * Returns a copy of this time with the specified amount added.
  * @param localTime
  * @param duration
  * @return
  */
 public static LocalTime modifyDates(LocalTime localTime, Duration duration) {
      return localTime.plus(duration);
 }

 /**
  * Obtains a Duration representing the duration between two temporal objects.
  * @param localTime1
  * @param localTime2
  * @return
  */
 public static Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) {
     return Duration.between(localTime1, localTime2);
 }

 /**
  * Get date and time by passing format
  * @param representation
  * @return
  */
 public static LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
     return LocalDateTime.parse(representation);
 }

 /**
  * Convert Date to Java 8 LocalDate
  * @param date
  * @return
  */
 public static LocalDateTime convertDateToLocalDate(Date date) {
     return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
 }

 /**
  * Convert Calender to LocalDate
  * @param calendar
  * @return
  */
 public static LocalDateTime convertDateToLocalDate(Calendar calendar) {
     return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
 }
 
}

Java8DateUtilityTest.java

package com.ramesh.java8.datetime;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

import org.junit.Test;

/**
 * JUnit test cases for Java8DateUtiliy Methods
 * @author javaguides.net
 *
 */
public class Java8DateUtilityTest {
 
 @Test
 public void getLocalDateFromClockTest() {
     System.out.println("Current date ::" +Java8DateUtility.getLocalDateFromClock());
     assertEquals(LocalDate.now(), Java8DateUtility.getLocalDateFromClock());
 }

 @Test
 public void getNextDayTest() {
     LocalDate date = Java8DateUtility.getNextDay(LocalDate.now());
     System.out.println("Next Day ::" + date);
     assertNotNull(date);
 }

 @Test
 public void getPreviousDayTest() {
     System.out.println("Get Previous Day :: " + Java8DateUtility.getPreviousDay(LocalDate.now()));
 }
 
 @Test
 public void getDayOfWeekTest() {
     System.out.println("Get Day Of Week :: " + Java8DateUtility.getDayOfWeek(LocalDate.now()));
 }

 @Test
 public void getFirstDayOfMonthTest() {
     System.out.println("Get First day of Month :: " + Java8DateUtility.getFirstDayOfMonth());
 }

 @Test
 public void getStartOfDayTest() {
     System.out.println("Get start of day :: " + Java8DateUtility.getStartOfDay(LocalDate.now()) );
 }

 @Test
 public void printCurrentDayMonthAndYearTest() {
     Java8DateUtility.printCurrentDayMonthAndYear();
 }

 @Test
 public void checkDateEqualsTest() {
     assertTrue(Java8DateUtility.checkDateEquals(LocalDate.now(), LocalDate.now()));
 }

 @Test
 public void getCurrentTime() {
     assertEquals(Java8DateUtility.getCurrentTime(), LocalTime.now());
 }

 @Test
 public void addHoursToTime() {
     System.out.println("Added hours to time :: " + Java8DateUtility.addHoursToTime(1));
 }

 @Test
 public void timeZoneTest() {
     System.out.println("America/Los_Angeles Zone :: " + Java8DateUtility.timeZone("America/Los_Angeles"));
 }

 @Test
 public void checkLeafYear() {
     Java8DateUtility.checkLeafYear();
 }

 @Test
 public void getTimeStamp() {
     System.out.println("get time stamp ::" + Java8DateUtility.getTimeStamp());
 }

 @Test
 public void getZonedDateTime() {
     System.out.println("" + Java8DateUtility.getZonedDateTime(LocalDateTime.now(), ZoneId.of("Europe/Paris")));
 }

 @Test
 public void getDifferenceBetweenDates() {
     System.out.println("Difference between two dates :: " + Java8DateUtility.getDifferenceBetweenDates(LocalTime.now(), LocalTime.now().plusHours(12)));
 }

 @Test
 public void getLocalDateTimeUsingParseMethod() {
     System.out.println("Get local date time using parse method :: " + Java8DateUtility.getLocalDateTimeUsingParseMethod(DateTimeFormatter.BASIC_ISO_DATE.toString()));
 }

 @Test
 public void convertDateToLocalDate() {
     System.out.println("Convert Date to LocalDate :: " + Java8DateUtility.convertDateToLocalDate(new Date()));
 }

 @Test
 public void convertCalenderToLocalDateTest() {
     System.out.println("Convert Calender to LocalDate :: " + Java8DateUtility.convertDateToLocalDate(Calendar.getInstance().getTime()));
 }
}
Run the JUnit test cases will print the output:
Next Day ::2018-07-22
Get Day Of Week :: SATURDAY
Get Previous Day :: 2018-07-20
Difference between two dates :: PT-12H
Time after 2 hours : 19:40:51.641
Added hours to time :: 19:40:51.641
2014 is not a Leap year
local time now : 18:40:51.642
What is value of this instant 2018-07-21T13:10:51.642Z
get time stamp ::2018-07-21T13:10:51.642Z
Convert Date to LocalDate :: 2018-07-21T18:40:51.657
Convert Calender to LocalDate :: 2018-07-21T18:40:51.660
Year : 2018 Month : 7 day : 21   
Today 2018-07-21 and date1 2018-07-21 are same date 
Current date ::2018-07-21
Get start of day :: 2018-07-21T00:00
Current date and time in a particular timezone : 2018-07-21T18:40:51.693-07:00[America/Los_Angeles]
America/Los_Angeles Zone :: 2018-07-21T18:40:51.693-07:00[America/Los_Angeles]
Get First day of Month :: 2018-07-01
2018-07-21T18:40:51.711+02:00[Europe/Paris]
Do comment if you have any other Java 8 Date Utility methods so that everyone can use it.

Comments