directory

preface

Date and time handling classes in jdk8 are different from those in JDk7.

Java 8 date/time classes

3. The relationship between date and time main classes (to be updated)

Four: date operation and processing

Gets the current date (accurate to date only)

Get the current time (accurate to milliseconds)

Gets the Monday date of the previous week

Get the specific year, month, day, hour, minute, and second

Specify the date and time

Determine if two dates are equal

Calculate the dates in years (before), months (before), days (before), etc

Determines how many days a given month has

Calculate the number of months, days, and minutes between two dates


preface

A long time ago, I summarized some common methods for time handling prior to the JDK7 release: converting dates to strings, adding dates after a specified time and a specified number of days, getting the time of last week and Monday, and so on; Specific you can click the link to view the full: blog.csdn.net/qq_27471405…

But these are not thread-safe and are not recommended, for example

In a class, there is the following code: private static SimpleDateFormat SDF = new SimpleDateFormat(” YYYY-MM-DD HH: MM: SS “); public String getDate(Date date){ return sdf.format(date); }

The code above is thread unsafe when it is concurrent. How is it unsafe

So today I’m going to share with you the public methods that will be handled some time after JDK8, which are thread-safe and should be used in the future

Date and time handling classes in jdk8 are different from those in JDk7.

\

  1. Java’s java.util.Date and java.util.Calendar classes are poorly used, do not support time zones, and are mutable, which means they are not thread-safe; \
  2. The DateFormat class for formatting dates is in the java.text package. It is an abstract class, so we need to instantiate a SimpleDateFormat object to handle date formatting, and DateFormat is also non-thread-safe. This means that if you call the same DateFormat object in a multithreaded program, you will get unexpected results. \
  3. The calculation of dates is cumbersome and error-prone because months start at zero, meaning that the month taken from the Calendar needs to be incremented by one to represent the current month \

As a result of these problems, a number of tripartite date processing frameworks have emerged, such as Joda-time, Data4J and other open source projects

Java 8 date/time classes

Java 8’s date and time classes include LocalDate, LocalTime, Instant, Duration, and Period, all of which are included in the java.time package.

  • Instant: indicates an Instant instance.
  • LocalDate: indicates the LocalDate, excluding the specific time, for example, 2014-01-14. This parameter is used to record birthdays, anniversaries, and franchise dates.
  • LocalTime: indicates the LocalTime, excluding the date.
  • LocalDateTime: Combines date and time, but does not contain time difference or time zone information.
  • ZonedDateTime: The most complete date time, including the time zone and the time difference from UTC or Greenwich.

The new API also introduces the ZoneOffSet and ZoneId classes to make time zones easier to resolve. The DateTimeFormatter class that parses and formats time has also been completely redesigned.

3. The relationship between date and time main classes (to be updated)

1. LocalDate diagram:

2, a LocalTime:

3, LocalDateTime:

4, OffsetTime:

5, OffsetDateTime:

6, ZonedDateTime:

7, Instant:

Four: date operation and processing

Gets the current date (accurate to date only)

Public static void getNowDate(String formatStr){if (String formatStr){if (String formatStr){if (String formatStr){if (String formatStr){if (String formatStr){if (StringUtils.isBlank(formatStr)){ formatStr = "yyyy-MM-dd"; } LocalDate now = LocalDate.now(); System.out.println(" current date: "+ now +" "+ now.getDayofweek ()); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr); / / * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * are pirated, other public no. : Zygxsq) String nowFormat = now.format(dateTimeFormatter); System.out.println(" formatted current date: "+nowFormat); }Copy the code

If the formatting to day hours seconds, will quote Exception: the Exception in the thread “is the main” Java. Time. Temporal. UnsupportedTemporalTypeException: Unsupported field: HourOfDay

Get the current time (accurate to milliseconds)

/ * * * get the current time (which can be accurate to ms) * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * are pirated, other public no. : Public static void getNowTime(String formatStr){if */ public static void getNowTime(String formatStr){if (StringUtils.isBlank(formatStr)){ formatStr = "yyyy-MM-dd"; } LocalDateTime now = LocalDateTime.now(); System.out.println(" current date: "+ now +" "+ now.getDayofweek ()); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr); / / * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * are pirated, other public no. : Zygxsq) String nowFormat = now.format(dateTimeFormatter); System.out.println(" formatted current date: "+nowFormat); }Copy the code

Gets the Monday date of the previous week

/ * * * to get the date of the last week on Monday * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * are pirated, other public no. : Zygxsq */ public static void getLastMonday(){LocalDate now = localdate.now (); System.out.println(" current date: "+ now +" "+ now.getDayofweek ()); LocalDate todayOfLastWeek = now.minusDays(7); LocalDate last_monday = todayOfLastWeek.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1); / / * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * are pirated, other public no. : Println (" last_monday: "+last_monday); zygxSq (zygxSq) system.out.println (" last_monday: "+last_monday); }Copy the code

Get the specific year, month, day, hour, minute, and second

@param formatStr */ public static void getDetailTime(String formatStr){LocalDateTime now = LocalDateTime.now(); System.out.println(" current date: "+ now +" "+ now.getDayofweek ()); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr); String nowFormat = now.format(dateTimeFormatter); System.out.println(" formatted current date: "+nowFormat); int year = now.getYear(); int month = now.getMonthValue(); int day = now.getDayOfMonth(); int hour = now.getHour(); int minute = now.getMinute(); int second = now.getSecond(); int nano = now.getNano(); System. Out. Printf (" years: % d: % d: % d hours: minutes: % d % d seconds: % d millisecond: % d % n ", year, month, day, hour, minute, second, the nano); / / * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * are pirated, other public number: shine notes (zygxsq)}Copy the code

Specify the date and time

/ * * * specified date, time, * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * other are pirated, the public no. : @param formatStr */ public static void createTime(String formatStr){LocalDate date = localdate.of (2020, 04, 27); System.out.println(" specify date: "+ date); LocalDateTime time = LocalDateTime. Of (2020, 04, 27,06,10,50); System.out.println(" time: "+ time); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr); String nowFormat = time.format(dateTimeFormatter); System.out.println(" formatted time: "+nowFormat); }Copy the code

Determine if two dates are equal

/ * * * determine whether two dates are equal, before and after * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * are pirated, other public no. : */ public static void compareDate(){LocalDate now = localdate.now (); System.out.println(" current time: "+ now +" "+ now.getDayofweek ()); LocalDate date1 = LocalDate.of(2020, 04, 27); LocalDate date2 = LocalDate.of(2020, 04, 27); LocalDate date3 = LocalDate.of(2020, 04, 28); boolean equal = now.isEqual(date1); System.out.printf(" is the same time: %s ", date1.equals(now)); System.out.printf(" is the same time: %s ", now.isequal (date1)); System.out.println(); System.out.printf(" is the same time: %s ", date1.equals(date2)); System.out.printf(" is the same time: %s ", date1.isequal (date2)); System.out.println(); System.out.println("data2(2020.4.27) is smaller than data3(2020.4.28) : "+ date2.isbefore (date3)); * * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 are pirated, other public no. : Println ("data2(2020.4.27) is larger than data3(2020.4.28) : "+date2. IsAfter (date3)); }Copy the code

Calculate the dates in years (before), months (before), days (before), etc

/ * * * computing (after a few years ago), a few months (before), a few days after (before) the date on which the * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * are pirated, other public no. : Public static void calculateTime(String formatStr){LocalDateTime now = LocalDateTime.now(); LocalDateTime newTime = now.plusHours(6); System.out.println(" current time: "+ now +" "+ now.getDayofweek ()); System.out.println(" time after 6 hours: "+ newTime); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr); String nowFormat = now.format(dateTimeFormatter); String newFormat = newTime.format(dateTimeFormatter); System.out.println(" formatted current time: "+nowFormat); System.out.println(" 6 hours after formatting: "+newFormat); LocalDateTime twoYearsLater = now.plusYears(2); String twoYearsFormat = twoYearsLater.format(dateTimeFormatter); System.out.println("2 yeartime: "+twoYearsFormat); LocalDateTime twoMonthsLater = now.plusMonths(2); String twoMonthsFormat = twoMonthsLater.format(dateTimeFormatter); System.out.println("2 months later: "+twoMonthsFormat); LocalDateTime twoWeeksLater = now.plusWeeks(2); String twoWeeksFormat = twoWeeksLater.format(dateTimeFormatter); System.out.println("2 weeks after time: "+twoWeeksFormat); LocalDateTime twoDaysLater = now.plusDays(2); String twoDaysFormat = twoDaysLater.format(dateTimeFormatter); System.out.println("2 days later: "+twoDaysFormat); LocalDateTime twoMinutesLater = now.plusMinutes(2); String twoMinutesFormat = twoMinutesLater.format(dateTimeFormatter); System.out.println(" time after 2 minutes: "+twoMinutesFormat); LocalDateTime twoMinutesBefore = now.plusMinutes(-2); String twoMinutesBeforeFormat = twoMinutesBefore.format(dateTimeFormatter); System.out.println("2 minutes ago time: "+twoMinutesBeforeFormat); / / / / original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 are pirated, other public no. : LocalDateTime twoYearsPlusLater = now.plus(2, ChronoUnit.YEARS); String twoYearsPlusLaterFormat = twoYearsPlusLater.format(dateTimeFormatter); System.out.println(" time after 2 years: "+twoYearsPlusLaterFormat); // The minus sign indicates the previous LocalDateTime twoDaysPlusBefore = now.plus(-2, chronounit.days); String twoDaysPlusBeforeFormat = twoDaysPlusBefore.format(dateTimeFormatter); System.out.println("2 days ago time: "+twoDaysPlusBeforeFormat); // LocalDateTime twoDaysMinusBefore = now. Minus (2, ChronoUnit.DAYS); // LocalDateTime twoDaysMinusBefore = now. String twoDaysMinusBeforeFormat = twoDaysMinusBefore.format(dateTimeFormatter); System.out.println("2 days ago time: "+twoDaysMinusBeforeFormat); }Copy the code

Determines how many days a given month has

Public static void getMonthDays(){YearMonth currentYearMonth = YearMonth.now(); / / public static void getMonthDays(){YearMonth currentYearMonth = YearMonth.now(); System.out.println(" currentYearMonth: "+currentYearMonth); System. The out. Println (" current month how many days: "+ currentYearMonth. LengthOfMonth ()); YearMonth february = YearMonth.of(2020, Month.FEBRUARY); System.out.println(" February: "+ February); System.out.println(" February. LengthOfMonth ()); }Copy the code

Calculate the number of months, days, and minutes between two dates

/ * * * calculation difference between two dates months, days, minutes * original article links: https://blog.csdn.net/qq_27471405/article/details/106824023 * other are pirated, the public no. : Public static void getDaysBetweenTwoDate(){LocalDate startDate = localdate.of (2020, 04, 27); public static void getDaysBetweenTwoDate(){LocalDate startDate = LocalDate. LocalDate endDate = LocalDate.of(2020, 07, 2); long months = startDate.until(endDate, ChronoUnit.MONTHS); long days = startDate.until(endDate, ChronoUnit.DAYS); System.out.println("startDate(2020.04.27) + endDate(2020.07.02) +months); System.out.println("startDate(2020.04.27) and endDate(2020.07.02) : "+days); StartTime = localdatetime. of(2020, 04, 27,18,20,10); LocalDateTime endTime = LocalDateTime. Of (2020, 04, 27,18,30,12); long minutes = startTime.until(endTime, ChronoUnit.MINUTES); System.out.println("startTime(2020.04.27 18:20:10) + endTime(2020.04.27 18:30:20) +minutes); / / https://blog.csdn.net/qq_27471405/article/details/106824023 * * original article link are pirated, other public number: shine notes (zygxsq)}Copy the code


Refer to the article

Blog.csdn.net/u012091080/…

Blog.csdn.net/chenleixing…

Blog.csdn.net/feicongcong…

Thanks to the original author’s sharing, so that the technical people can solve the problem faster

My blog is synchronized to tencent cloud + community, invite everyone to come together: cloud.tencent.com/developer/s…