Please refer to java8 localdatetime and other time user manuals (all), mark them first and then read them

Preface

Java 8's time and date api provides us with great convenience. How to be familiar with the use of time api is also a very important knowledge point for learning java 8. Let's learn together.

This article has a lot of code, which can be used as a tool. When you need to use it, please refer to it again.

Catalog

1. How to convert a normal Date time to a LocalDateTime?

The above is the operation steps of converting a common Date object to java8 time. You need to pay special attention to the time zone.

    // Set time zone
//      ZoneId defaultZoneId = ZoneId.systemDefault();
        ZoneId defaultZoneId = ZoneId.of("Asia/Shanghai");
        System.out.println("set  TimeZone : "   defaultZoneId);

        //Each of the following notes is the output

        //date : Fri Jan 17 16:52:59 CST 2020
        Date date = new Date();
        System.out.println("date : "   date);

        //1. instant : 2020-01-17T08:52:59.235Z
        Instant instant = date.toInstant();
        System.out.println("instant : "   instant); //Zone: the default is UTC 0 time zone

        //2. localDate : 2020-01-17
        LocalDate localDate = instant.atZone(defaultZoneId).toLocalDate();
        System.out.println("localDate : "   localDate);

        //3. LocalDateTime: 2020-01-17T16:52:59.235
        LocalDateTime localDateTime = instant.atZone(defaultZoneId).toLocalDateTime();
        System.out.println("localDateTime : "   localDateTime);

        //4. ZonedDateTime: 2020-01-17T16:52:59.235 08:00[Asia/Shanghai]
        ZonedDateTime zonedDateTime = instant.atZone(defaultZoneId);
        System.out.println("zonedDateTime : "   zonedDateTime);

2. How to convert java8 time to normal Date?

The conversion process is just the opposite of the above legend, and the code is as follows:

  //Similarly, we set the time zone to Shanghai
        ZoneId defaultZoneId = ZoneId.of("Asia/Shanghai");
        System.out.println(" Default TimeZone : "   defaultZoneId);

        LocalDate localDate = LocalDate.of(2020, 01, 17);
        Date date = Date.from(localDate.atStartOfDay(defaultZoneId).toInstant());
        System.out.println("\n1. LocalDate -> Date");
        System.out.println("localDate : "   localDate);
        System.out.println("date : "   date);

        LocalDateTime localDateTime = LocalDateTime.of(2020,01,17,17,46,31);
        Date date2 = Date.from(localDateTime.atZone(defaultZoneId).toInstant());
        System.out.println("\n2. LocalDateTime -> Date");
        System.out.println("localDateTime : "   localDateTime);
        System.out.println("date2 : "   date2);

        ZonedDateTime zonedDateTime = localDateTime.atZone(defaultZoneId);
        Date date3 = Date.from(zonedDateTime.toInstant());
        System.out.println("\n3. ZonedDateTime -> Date");
        System.out.println("zonedDateTime : "   zonedDateTime);
        System.out.println("date3 : "   date3);

3. How to compare time?

  • Whether it's Date, or localDate and localDateTime in java8, you can use the
    compareTo method to compare time.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2020-01-17");
Date date2 = sdf.parse("2020-01-16");
System.out.println("The former is positive if larger, equal to 0, less than negative : "   date1.compareTo(date2));

LocalDate and LocalDateTime provide three methods, isAfter(),isBefore(),isEqual().

Before java8, we used after(), before(), equals. The method names are different, but the functions are similar.

4. Instant in java8

Instant represents an instantaneous point in time value object.

It is calculated from 1970-01-01T00:00:00Z. It is immutable and thread safe.

5. How to get the current time stamp?

Mode 1: new Timestamp(System.currentTimeMillis());

Method 2: new Date().getTime();

Mode 3: Instant.

Mode 4: Calendar.getInstance()

Mode 5: LocalDateTime.now()

Mode 6: LocalDate.now()

Timestamp timestamp = new Timestamp(System.currentTimeMillis());

//2020-01-17 17:04:53.346
System.out.println(timestamp);

//return 1579251953703
System.out.println(timestamp.getTime());

// Timestamp conversion to instant 2020-01-17T09:05:53.703Z
Instant instant = timestamp.toInstant();
System.out.println(instant);

//return 1579251953703
System.out.println(instant.toEpochMilli());

//  instant to timestamp 1579251893346
Timestamp tsFromInstant = Timestamp.from(instant);
System.out.println(tsFromInstant.getTime());

6. Time to String

We all know that we usually use SimpleDateFormat to realize the conversion of time and string, but the improper use of this api may cause thread safety problems. Here, we recommend the following methods to do the conversion to ensure thread safety.

   //Use current time test
LocalDateTime now = LocalDateTime.now();

System.out.println("Before : "   now);

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

String formatDateTime = now.format(formatter);

System.out.println("After : "   formatDateTime);

7.String transfer time

String now = "2020-01-17 17:30";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

LocalDateTime formatDateTime = LocalDateTime.parse(now, formatter);

System.out.println("Before : "   now);

System.out.println("After : "   formatDateTime);

System.out.println("After : "   formatDateTime.format(formatter));

8.Instant to LocalDateTime

Instant instant = Instant.now();
System.out.println("Instant : "   instant);

// Add time zone as Shanghai
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai"));
System.out.println("LocalDateTime : "   ldt);


9. Transfer localdatetime to Instant

LocalDateTime dateTime = LocalDateTime.of(2020, 01, 17, 6, 17, 10);

//LocalDateTime : 2020-01-17T06:17:10
System.out.println("LocalDateTime : "   dateTime);

//  HH: mmif the time zone is set to East 8, it will be 8 hours later than the original time
//Instant : 2020-01-16T22:17:10Z
Instant instant = dateTime.toInstant(ZoneOffset.of(" 08:00"));
System.out.println("Instant : "   instant);

10. Why do java8 have localDate and localDateTime?

Before java8, time was represented by Date class and so on, including some poor API designs. For example, the year java.util.Date starts from 1900, the month starts from 1, and the day starts from 0, which is not intuitive. Third party Date and time libraries have made up for some of this popularity, such as joda time.

In order to solve these problems and provide better support in the JDK kernel, a new date and time API is designed for Java SE 8 without these problems.

Java SE 8 comes with a new date and time API, which provides developers with greatly improved security and functionality. The new API models the domain well and provides a large number of classes for modeling various developer use cases.

Welcome to the public number [Development Notes for Xia Meng], reply to dry goods, and pick up a selected learning video.

103 original articles published, 21 praised, 190000 visitors+
Private letter follow

Keywords: Java less JDK

Added by dc277 on Fri, 17 Jan 2020 13:44:36 +0200