Date, DateTime, Instant in java8

Date, DateTime, Instant in java8

localDate

Contains year, month, and day

LocalDate.of(2018, 1, 27) //或 LocalDate.of(2018, Month.JANUARY, 27)

 => 2014-1-27

 

LocalTime

Contains only hours, minutes, seconds, nanoseconds

LocalTime.of(3, 30, 20)

=> 03:30:20

 

LocalDateTime

Combines LocalDate and LocalTime

LocalDateTime.of(2018, 1, 27, 3, 30, 20)

=> 2018-01-27T03:30:20

 

ZoneDateTime

time with time zone information

ZonedDateTime.of(LocalDateTime.of(2018, 1, 27, 3, 30, 20), ZoneId.of("+08"));

=> 2018-01-27T03:30:20+08:00

 

Instant

Use long to represent the nanosecond from 1970-1-1 00:00:00 to the present

Instant.now()// Get the current time

=> 2018-01-27T14:40:41.487Z

 

The above classes all provide operations on time zone contention:

Instant.now().atOffset(ZoneOffset.ofHours(8))// Get Beijing time

2018-01-27T22:40:41.486+08:00

 

Convert date and time to specified format

//Use long to represent milliseconds from 1970-1-1 00:00:00 to the present

long currentTime = System.currentTimeMillis();

Date date = new Date(currentTime);

//More friendly way to show date and time to client

// yyyy-MM-dd HH:mm:ss

//specify a format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Convert the date to a string in the specified format

String dateTime = sdf.format(date);

=> 2018-01-27 14:40:41

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325612324&siteId=291194637