Java 8 DateUtility日期实用类

x33g5p2x  于2022-10-06 转载在 Java  
字(9.6k)|赞(0)|评价(0)|浏览(358)

在这篇文章中,我们将讨论几个常用的Java 8日期时间实用方法。我们还可以向您展示所有Java 8日期实用方法的样本JUnittest case。

Java 8 Date Utility Class包含了与日期和时间有关的实用方法,您可以在日常的项目工作中使用这些方法。

不要忘记查看我们的Java 8日期时间API教程的成果

Java8 DateUtility类方法

  • getLocalDateFromClock() - 获取当前本地日期。
  • LocalDate getNextDay(LocalDate localDate) - 获得第二天的日期。
  • LocalDate getNextDay(LocalDate localDate) - 获得下一天。
  • LocalDate getPreviousDay(LocalDate localDate) - 获得前一天。
  • DayOfWeek getDayOfWeek(LocalDate localDate) - 获得一周的日子。
  • LocalDate getFirstDayOfMonth() - 获得本月的第一天。
  • LocalDateTime getStartOfDay(LocalDate localDate) - 获得一天的开始。
  • printCurrentDayMonthAndYear() - 以日、月、年的格式打印当前时间。
  • checkDateEquals(LocalDate date, LocalDate today) - 检查两个日期是否相等。
  • LocalTime getCurrentTime() - 获取当前时间。
  • LocalTime addHoursToTime(int hours) - 向时间添加小时。
  • ZonedDateTime timeZone(String timeZone) - 按地区获取日期和时间。
  • checkLeafYear() - 检查叶子的年份。
  • Instant getTimeStamp() - 获得时间戳。
  • LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds)  - 按小时、分钟和秒获取日期。
  • ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) - 获得区域日期时间。
  • LocalTime modifyDates(LocalTime localTime, Duration duration) - 返回这个时间的副本,并加上指定的数量。
  • Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) - 获得代表两个时间对象之间的持续时间的Duration。
  • LocalDateTime getLocalDateTimeUsingParseMethod(String representation) - 通过传递格式获得日期和时间。
  • LocalDateTime convertDateToLocalDate(Date date) - 将日期转换成Java 8 LocalDate。
  • LocalDateTime convertDateToLocalDate(Calendar calendar) - 将日历转换成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()));
 }
}

运行JUnit测试案例将打印输出。

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]

相关文章

微信公众号

最新文章

更多