+2

Java SE 8 Oracle Certified Associate 1Z0-808 - #15

1. Câu hỏi

2. Phân tích

Đây là một câu hỏi kiểm tra kiến thức của LocalDate và LocalTime classes

     public static void main(String [] args) {
         LocalDate date = LocalDate.parse("1947-08-14");
         LocalTime time = LocalTime.MAX;
         System.out.println(date.atTime(time));
     }

2.1. Phân tích hàm LocalDate.parse() xem docs

public static LocalDate parse(CharSequence text)
Obtains an instance of LocalDate from a text string such as 2007-12-03.
The string must represent a valid date and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.

Parameters:
text - the text to parse such as "2007-12-03", not null
Returns:
the parsed local date, not null
Throws:
DateTimeParseException - if the text cannot be parsed

Hàm này không truyền format vào nên nó lấy theo format mặc định DateTimeFormatter.ISO_LOCAL_DATE Do đó text truyền vào 1947-08-14 là hợp lệ year=1947, month-of_year=08 và day-of-month=14

public static final DateTimeFormatter ISO_LOCAL_DATE
The ISO date formatter that formats or parses a date without an offset, such as '2011-12-03'.
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended local date format. The format consists of:

Four digits or more for the year. Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits. Years outside that range will have a prefixed positive or negative symbol.
A dash
Two digits for the month-of-year. This is pre-padded by zero to ensure two digits.
A dash
Two digits for the day-of-month. This is pre-padded by zero to ensure two digits.
The returned formatter has a chronology of ISO set to ensure dates in other calendar systems are correctly converted. It has no override zone and uses the STRICT resolver style.

2.2. Phân tích hàm tạo biến LocalTime

LocalTime time = LocalTime.MAX;

Đọc docs ta sẽ thấy giá trị của time = '23:59:59.999999999'

public static final LocalTime MAX
The maximum supported LocalTime, '23:59:59.999999999'. This is the time just before midnight at the end of the day.

2.3. Check code hàm atTime của LocalDate

System.out.println(date.atTime(time));

Đọc docs , như vậy hàm này sẽ trả về LocalDateTime với giá trị được tạo bỏi LocalDate và LocalTime.

public LocalDateTime atTime(LocalTime time)
Combines this date with a time to create a LocalDateTime.
This returns a LocalDateTime formed from this date at the specified time. All possible combinations of date and time are valid.

Specified by:
atTime in interface ChronoLocalDate
Parameters:
time - the time to combine with, not null
Returns:
the local date-time formed from this date and the specified time, not null

Giá trị localDateTime là 1947-08-14T23:59:59.999999999

Đáp án: image.png

3. Kết luận

Bạn có thể gõ code vào IDE để chạy lại và kiểm tra Source cho câu hỏi


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí