This article source: making here | | GitEE, click here

1. Time and date

In the system development, date and time, as important business factors, play a very key role, such as data generation under the same time node, various data statistics and analysis based on time range, cluster nodes to unify the time to avoid timeout, etc.

There are several key concepts in time and date:

  • Date: Usually a combination of year, month and day indicates the current date.
  • Time: Usually a combination of minutes and seconds represents the current time.
  • Time zone: the longitude of countries and regions in the world is different, divided into 24 standard time zones, adjacent time zones differ by one hour.
  • Timestamp: Time from UTC1970-1-1 00:00:00The total number of seconds up to now.

The use of date and time in the system is usually the acquisition of time and some common calculation and format conversion processing, in some time zone dependent business can become much more complex, such as in e-commerce business global trade or overseas online shopping, etc.

The JDK native API

1. Date basis

Basic usage

Java.sql.Date inherits java.util.Date, and most of the related methods call the parent methods directly.

public class DateTime01 { public static void main(String[] args) { long nowTime = System.currentTimeMillis() ; java.util.Date data01 = new java.util.Date(nowTime); java.sql.Date date02 = new java.sql.Date(nowTime); System.out.println(data01); System.out.println(date02.getTime()); }} Print: Fri Jan 29 15:11:25 CST 2021 1611904285848

Calculation rules

public class DateTime02 { public static void main(String[] args) { Date nowDate = new Date(); System. The out. Println (" : "+ nowDate. GetYear ()); System. The out. Println (" : "+ nowDate. GetMonth ()); System. The out. Println (" : "+ nowDate. GetDay ()); }}

Year: current time minus 1900;

public int getYear() {
    return normalize().getYear() - 1900;
}

Month: 0-11 denotes January to December;

public int getMonth() {
    return normalize().getMonth() - 1;
}

2. Normal expression;

public int getDay() {
    return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;
}

Format conversion

A non-thread-safe date conversion API, which is not allowed in the development of the specification.

Public class dateTime02 {public static void main(String[] args) throws Exception new SimpleDateFormat() ; String nowDate01 = dateFormat01.format(new Date()) ; System.out.println("nowDate01="+nowDate01); String format = "yyyy-mm-dd HH: MM :ss"; String format =" yyyy-mm-dd HH: MM :ss"; SimpleDateFormat dateFormat02 = new SimpleDateFormat(format); String nowDate02 = dateFormat02.format(new Date()) ; System.out.println("nowDate02="+nowDate02); String parse = "yyyy-mm-dd HH: MM "; SimpleDateFormat dateFormat03 = new SimpleDateFormat(parse); Date parseDate = dateFormat03.parse("2021-01-18 16:59:59") ; System.out.println("parseDate="+parseDate); }}

The Date class has been used in projects since the initial version of the JDK as a Date and time, but the methods of the related API have been largely deprecated in the form of a second encapsulated time component. This API has some of the worst design in Java.

2. Calendar updates

Calendar, as an abstract class that defines methods for date-time related transformations and calculations, is visually visible

public class DateTime04 { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR,2021); calendar.set(Calendar.MONTH,1); calendar.set(Calendar.DAY_OF_MONTH,12); calendar.set(Calendar.HOUR_OF_DAY,23); calendar.set(Calendar.MINUTE,59); calendar.set(Calendar.SECOND,59); calendar.set(Calendar.MILLISECOND,0); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ; Date defDate = calendar.getTime(); System.out.println(defDate+"||"+dateFormat.format(defDate)); }} output: Fri Feb 12 23:59:59 CST 2021 | | 2021-02-12 23:59:59

The intuitive feeling is that the relevant methods in Date migrate the implementation of Calendar, the simplified function of Date focuses on the entity encapsulation of Date and time, the complex calculation strategy of Calendar, and the DateFormat is still used for format processing. But Calendar is still rarely used, as the basic API above illustrates.

3. Update the JDK1.8 API

In later versions of Java8, the core API classes include LocalDate -date, LocalTime -time, and LocalDateTime -date plus time.

  • LocalDate: The date description is an immutable class for final modifiers, in the default format yyyy-mm-dd.
  • LocalTime: The time description is an immutable class for final modifiers, in the default format of hh:mm:ss.zzz.
  • LocalDateTime: Date and time Immutable class that describes final modifiers.
Public class dateTime05 {public static void main(String[] args) {System.out.println(localDate.now ()); Println (localtime.now ()); println(localtime.now ()); println(localtime.now ()); System.out.println(localDateTime.now ()); System.out.println(localDateTime.now ()); LocalDate = localDate. Now (); System.out.println("[" + localDate.getYear() + "year]; [" + LocalDate.getMonthValue () + "month]; [" + localDate.getDayOfMonth()+" day]"); Println ("1 year after: "+ localDate.plusYears(1)); // System.out.println(" + localDate.plusYears(1)); System.out.println(" February before: "+ localDate.minusMonths(2)); System.out.println("3 weeks after: "+ localDate.plusWeeks(3)); System.out.println("3 days ago: "+ localdate.minusDays (3)); LocalTime1 = localTime. Of (12, 45, 45); ; LocalTime localTime2 = LocalTime.of(16, 30, 30); ; System.out.println(localTime1.isAfter(localTime2)); System.out.println(localTime2.isAfter(localTime1)); System.out.println(localTime2.equals(localTime1)); // Date and time format localDateTime localDateTime = localDateTime.now (); LocalDate myLocalDate = localDateTime.toLocalDate(); LocalTime myLocalTime = localDateTime.toLocalTime(); Println (" Date: "+ myLocalDate); System.out.println(" time: "+ myLocalTime); }}

If you are a deep user of the Jodatime component, there is little pressure to use these APIs.

4. Time stamp

Time-stamps are also common in business, and are based on the Long type to represent time, which in many cases is far more useful than the regular date and time format.

Public class dateTime06 {public static void main(String[] args) {public static void main(String[] args) System.out.println(System.currentTimeMillis()); System.out.println(new Date().getTime()); System.out.println(Calendar.getInstance().getTime().getTime()); System.out.println(LocalDateTime.now().toInstant( ZoneOffset.of("+8")).toEpochMilli()); }}

It is important to note that in the real business, since there are various ways to obtain the timestamp, it is recommended to unify the tool method and specify the accuracy, so as to avoid the problem of partial accuracy to second and partial accuracy to millisecond, so as to avoid the conversion between the use of the situation.

Jodatime components

The Jodatime component was a common choice on most systems prior to Java8, with a lot of handy date and time processing encapsulated.

Base Dependency:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
</dependency>

Make a simple tool class wrapper on top of the components provided by Joda-Time to ensure the same style of business processing.

Public static final String DATE_FORMAT = "yyyy-mm-dd HH: MM :ss"; public static final String DATE_FORMAT =" yyyy-mm-dd HH: MM :ss"; Private JodTimeUtil (){} public static DateTime getCurrentTime (){return new DataTime (); } public static dateTime getDateTime (Object obj){return new dateTime (obj); } / / the time converting to specify the format String public static String getNowDate (the Date the Date, String format){ return new DateTime(date).toString(format) ; } public static String getWeek (Object Date){dateTime = dateTime (Date); String week = null ; The switch (time getDayOfWeek ()) {case DateTimeConstants. SUNDAY: week = "SUNDAY"; break; Case DateTimeConstants. MONDAY: week = "MONDAY"; break; Case DateTimeConstants. TUESDAY: week = "TUESDAY"; break; Case DateTimeConstants. WEDNESDAY: week = "WEDNESDAY"; break; Case DateTimeConstants. THURSDAY: week = "THURSDAY"; break; Case DateTimeConstants. FRIDAY: week = "FRIDAY"; break; Case DateTimeConstants. SATURDAY: week = "SATURDAY"; break; default: break; } return week ; }}

Four, the source code address

Making address GitEE, https://github.com/cicadasmile/java-base-parent, https://gitee.com/cicadasmile/java-base-parent

Read labels

【 JAVA Foundation 】【 Design Patterns 】【 Structure and Algorithms 】【Linux System 】【 Database 】【 Distributed Architecture 】【 Micro Services 】 】 Big Data Components 】【SpringBoot Advanced 】【Spring&Boot Foundation 】 Data Analysis 】【 Technical Map 】【 Workplace 】