Java 8 DateUtility日期实用类

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

在这篇文章中,我们将讨论几个常用的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

  1. package com.ramesh.java8.datetime;
  2. import java.time.DayOfWeek;
  3. import java.time.Duration;
  4. import java.time.Instant;
  5. import java.time.LocalDate;
  6. import java.time.LocalDateTime;
  7. import java.time.LocalTime;
  8. import java.time.ZoneId;
  9. import java.time.ZonedDateTime;
  10. import java.time.temporal.ChronoUnit;
  11. import java.time.temporal.TemporalAdjusters;
  12. import java.util.Calendar;
  13. import java.util.Date;
  14. /**
  15. * Useful Java8DateUtiliy Methods
  16. * @author javaguides.net
  17. *
  18. */
  19. public final class Java8DateUtility {
  20. /**
  21. * Get current local date.
  22. * @return
  23. */
  24. public static LocalDate getLocalDateFromClock() {
  25. return LocalDate.now();
  26. }
  27. /**
  28. * Get next day.
  29. * @param localDate
  30. * @return
  31. */
  32. public static LocalDate getNextDay(LocalDate localDate) {
  33. return localDate.plusDays(1);
  34. }
  35. /**
  36. * Get Previous Day.
  37. * @param localDate
  38. * @return
  39. */
  40. public static LocalDate getPreviousDay(LocalDate localDate) {
  41. return localDate.minus(1, ChronoUnit.DAYS);
  42. }
  43. /**
  44. * Get day of the week.
  45. * @param localDate
  46. * @return
  47. */
  48. public static DayOfWeek getDayOfWeek(LocalDate localDate) {
  49. DayOfWeek day = localDate.getDayOfWeek();
  50. return day;
  51. }
  52. /**
  53. * Get first day of the Month.
  54. * @return LocalDate
  55. */
  56. public static LocalDate getFirstDayOfMonth() {
  57. LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
  58. return firstDayOfMonth;
  59. }
  60. /**
  61. * Get start of the Day.
  62. * @param localDate
  63. * @return
  64. */
  65. public static LocalDateTime getStartOfDay(LocalDate localDate) {
  66. LocalDateTime startofDay = localDate.atStartOfDay();
  67. return startofDay;
  68. }
  69. /**
  70. * Print current time in day,month and year format.
  71. */
  72. public static void printCurrentDayMonthAndYear() {
  73. LocalDate today = LocalDate.now();
  74. int year = today.getYear();
  75. int month = today.getMonthValue();
  76. int day = today.getDayOfMonth();
  77. System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day);
  78. }
  79. /**
  80. * Check two dates are equals.
  81. * @param date
  82. * @param today
  83. * @return
  84. */
  85. public static boolean checkDateEquals(LocalDate date, LocalDate today) {
  86. if (date.equals(today)) {
  87. System.out.printf("Today %s and date1 %s are same date %n", today, date);
  88. return true;
  89. }
  90. return false;
  91. }
  92. /**
  93. * Get current time.
  94. * @return
  95. */
  96. public static LocalTime getCurrentTime() {
  97. LocalTime time = LocalTime.now();
  98. System.out.println("local time now : " + time);
  99. return time;
  100. }
  101. /**
  102. * Add hours to time.
  103. * @param hours
  104. * @return
  105. */
  106. public static LocalTime addHoursToTime(int hours) {
  107. LocalTime time = LocalTime.now();
  108. LocalTime newTime = time.plusHours(hours); // adding two hours
  109. System.out.println("Time after 2 hours : " + newTime);
  110. return newTime;
  111. }
  112. /**
  113. * Get date and time by zone.
  114. * @param timeZone
  115. * @return
  116. */
  117. public static ZonedDateTime timeZone(String timeZone) {
  118. ZoneId america = ZoneId.of(timeZone);
  119. LocalDateTime localtDateAndTime = LocalDateTime.now();
  120. ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america);
  121. System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork);
  122. return dateAndTimeInNewYork;
  123. }
  124. /**
  125. * Check for leap year.
  126. */
  127. public static void checkLeapYear() {
  128. LocalDate today = LocalDate.now();
  129. if (today.isLeapYear()) {
  130. System.out.println("This year is Leap year");
  131. } else {
  132. System.out.println("2014 is not a Leap year");
  133. }
  134. }
  135. /**
  136. * get time stamp.
  137. * @return
  138. */
  139. public static Instant getTimeStamp() {
  140. Instant timestamp = Instant.now();
  141. System.out.println("What is value of this instant " + timestamp);
  142. return timestamp;
  143. }
  144. /**
  145. * Get Date by hour,minute and seconds.
  146. * @param hour
  147. * @param min
  148. * @param seconds
  149. * @return
  150. */
  151. public static LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
  152. return LocalTime.of(hour, min, seconds);
  153. }
  154. /**
  155. * Get zone date time.
  156. * @param localDateTime
  157. * @param zoneId
  158. * @return
  159. */
  160. public static ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
  161. return ZonedDateTime.of(localDateTime, zoneId);
  162. }
  163. /**
  164. * Returns a copy of this time with the specified amount added.
  165. * @param localTime
  166. * @param duration
  167. * @return
  168. */
  169. public static LocalTime modifyDates(LocalTime localTime, Duration duration) {
  170. return localTime.plus(duration);
  171. }
  172. /**
  173. * Obtains a Duration representing the duration between two temporal objects.
  174. * @param localTime1
  175. * @param localTime2
  176. * @return
  177. */
  178. public static Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) {
  179. return Duration.between(localTime1, localTime2);
  180. }
  181. /**
  182. * Get date and time by passing format
  183. * @param representation
  184. * @return
  185. */
  186. public static LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
  187. return LocalDateTime.parse(representation);
  188. }
  189. /**
  190. * Convert Date to Java 8 LocalDate
  191. * @param date
  192. * @return
  193. */
  194. public static LocalDateTime convertDateToLocalDate(Date date) {
  195. return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
  196. }
  197. /**
  198. * Convert Calender to LocalDate
  199. * @param calendar
  200. * @return
  201. */
  202. public static LocalDateTime convertDateToLocalDate(Calendar calendar) {
  203. return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
  204. }
  205. }

Java8DateUtilityTest.java

  1. package com.ramesh.java8.datetime;
  2. import static org.junit.Assert.assertEquals;
  3. import static org.junit.Assert.assertNotNull;
  4. import static org.junit.Assert.assertTrue;
  5. import java.time.LocalDate;
  6. import java.time.LocalDateTime;
  7. import java.time.LocalTime;
  8. import java.time.ZoneId;
  9. import java.time.format.DateTimeFormatter;
  10. import java.util.Calendar;
  11. import java.util.Date;
  12. import org.junit.Test;
  13. /**
  14. * JUnit test cases for Java8DateUtiliy Methods
  15. * @author javaguides.net
  16. *
  17. */
  18. public class Java8DateUtilityTest {
  19. @Test
  20. public void getLocalDateFromClockTest() {
  21. System.out.println("Current date ::" +Java8DateUtility.getLocalDateFromClock());
  22. assertEquals(LocalDate.now(), Java8DateUtility.getLocalDateFromClock());
  23. }
  24. @Test
  25. public void getNextDayTest() {
  26. LocalDate date = Java8DateUtility.getNextDay(LocalDate.now());
  27. System.out.println("Next Day ::" + date);
  28. assertNotNull(date);
  29. }
  30. @Test
  31. public void getPreviousDayTest() {
  32. System.out.println("Get Previous Day :: " + Java8DateUtility.getPreviousDay(LocalDate.now()));
  33. }
  34. @Test
  35. public void getDayOfWeekTest() {
  36. System.out.println("Get Day Of Week :: " + Java8DateUtility.getDayOfWeek(LocalDate.now()));
  37. }
  38. @Test
  39. public void getFirstDayOfMonthTest() {
  40. System.out.println("Get First day of Month :: " + Java8DateUtility.getFirstDayOfMonth());
  41. }
  42. @Test
  43. public void getStartOfDayTest() {
  44. System.out.println("Get start of day :: " + Java8DateUtility.getStartOfDay(LocalDate.now()) );
  45. }
  46. @Test
  47. public void printCurrentDayMonthAndYearTest() {
  48. Java8DateUtility.printCurrentDayMonthAndYear();
  49. }
  50. @Test
  51. public void checkDateEqualsTest() {
  52. assertTrue(Java8DateUtility.checkDateEquals(LocalDate.now(), LocalDate.now()));
  53. }
  54. @Test
  55. public void getCurrentTime() {
  56. assertEquals(Java8DateUtility.getCurrentTime(), LocalTime.now());
  57. }
  58. @Test
  59. public void addHoursToTime() {
  60. System.out.println("Added hours to time :: " + Java8DateUtility.addHoursToTime(1));
  61. }
  62. @Test
  63. public void timeZoneTest() {
  64. System.out.println("America/Los_Angeles Zone :: " + Java8DateUtility.timeZone("America/Los_Angeles"));
  65. }
  66. @Test
  67. public void checkLeafYear() {
  68. Java8DateUtility.checkLeafYear();
  69. }
  70. @Test
  71. public void getTimeStamp() {
  72. System.out.println("get time stamp ::" + Java8DateUtility.getTimeStamp());
  73. }
  74. @Test
  75. public void getZonedDateTime() {
  76. System.out.println("" + Java8DateUtility.getZonedDateTime(LocalDateTime.now(), ZoneId.of("Europe/Paris")));
  77. }
  78. @Test
  79. public void getDifferenceBetweenDates() {
  80. System.out.println("Difference between two dates :: " + Java8DateUtility.getDifferenceBetweenDates(LocalTime.now(), LocalTime.now().plusHours(12)));
  81. }
  82. @Test
  83. public void getLocalDateTimeUsingParseMethod() {
  84. System.out.println("Get local date time using parse method :: " + Java8DateUtility.getLocalDateTimeUsingParseMethod(DateTimeFormatter.BASIC_ISO_DATE.toString()));
  85. }
  86. @Test
  87. public void convertDateToLocalDate() {
  88. System.out.println("Convert Date to LocalDate :: " + Java8DateUtility.convertDateToLocalDate(new Date()));
  89. }
  90. @Test
  91. public void convertCalenderToLocalDateTest() {
  92. System.out.println("Convert Calender to LocalDate :: " + Java8DateUtility.convertDateToLocalDate(Calendar.getInstance().getTime()));
  93. }
  94. }

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

  1. Next Day ::2018-07-22
  2. Get Day Of Week :: SATURDAY
  3. Get Previous Day :: 2018-07-20
  4. Difference between two dates :: PT-12H
  5. Time after 2 hours : 19:40:51.641
  6. Added hours to time :: 19:40:51.641
  7. 2014 is not a Leap year
  8. local time now : 18:40:51.642
  9. What is value of this instant 2018-07-21T13:10:51.642Z
  10. get time stamp ::2018-07-21T13:10:51.642Z
  11. Convert Date to LocalDate :: 2018-07-21T18:40:51.657
  12. Convert Calender to LocalDate :: 2018-07-21T18:40:51.660
  13. Year : 2018 Month : 7 day : 21
  14. Today 2018-07-21 and date1 2018-07-21 are same date
  15. Current date ::2018-07-21
  16. Get start of day :: 2018-07-21T00:00
  17. Current date and time in a particular timezone : 2018-07-21T18:40:51.693-07:00[America/Los_Angeles]
  18. America/Los_Angeles Zone :: 2018-07-21T18:40:51.693-07:00[America/Los_Angeles]
  19. Get First day of Month :: 2018-07-01
  20. 2018-07-21T18:40:51.711+02:00[Europe/Paris]

相关文章

最新文章

更多