2016-02-01 21 views
5

Nó là rất dễ dàng để phân tích ngày hết hạn của thẻ ghi nợ thẻ tín dụng/với thời gian Joda:Java 8: Cách phân tích ngày hết hạn của thẻ ghi nợ?

org.joda.time.format.DateTimeFormatter dateTimeFormatter = org.joda.time.format.DateTimeFormat.forPattern("MMyy").withZone(DateTimeZone.forID("UTC")); 
org.joda.time.DateTime jodaDateTime = dateTimeFormatter.parseDateTime("0216"); 
System.out.println(jodaDateTime); 

Out: 2016-02-01T00:00:00.000Z

Tôi cố gắng để làm điều tương tự nhưng với Java Time API:

java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("MMyy").withZone(ZoneId.of("UTC")); 
java.time.LocalDate localDate = java.time.LocalDate.parse("0216", formatter); 
System.out.println(localDate); 

Đầu ra:

Gây ra bởi: java.time.DateTimeException: Unabl e để lấy LocalDate từ TemporalAccessor: {MonthOfYear = 2, Year = 2016}, ISO, UTC loại java.time.format.Parsed tại java.time.LocalDate.from (LocalDate.java:368) tại java .time.format.Parsed.query (Parsed.java:226) tại java.time.format.DateTimeFormatter.parse (DateTimeFormatter.java:1851) ... 30 hơn

Nơi tôi đã phạm sai lầm và làm thế nào để giải quyết nó?

+0

Nó có vẻ như một ngày địa phương không thể được như rộng một lĩnh vực như bạn đã muốn. Địa phương yêu cầu một ngày. – Fallenreaper

Trả lời

10

A LocalDate đại diện cho ngày bao gồm một năm, một tháng và một ngày. Bạn không thể thực hiện một số LocalDate nếu bạn không xác định ba trường đó. Trong trường hợp này, bạn đang phân tích cú pháp một tháng và một năm, nhưng không có ngày nào. Như vậy, bạn không thể phân tích cú pháp trong một số LocalDate.

Nếu ngày là không thích hợp, bạn có thể phân tích nó thành một đối tượng YearMonth:

YearMonth là một đối tượng ngày thời gian bất biến đại diện cho sự kết hợp của một năm và tháng.

public static void main(String[] args) { 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMyy").withZone(ZoneId.of("UTC")); 
    YearMonth yearMonth = YearMonth.parse("0216", formatter); 
    System.out.println(yearMonth); // prints "2016-02" 
} 

Sau đó, bạn có thể biến đổi này YearMonth thành một LocalDate bằng cách điều chỉnh nó vào ngày đầu tiên của tháng ví dụ:

LocalDate localDate = yearMonth.atDay(1); 
+6

Con đường để đi - mặc dù trong trường hợp của một thẻ tín dụng nó có lẽ sẽ là 'LocalDate expiry = yearMonth.atEndOfMonth();'. – assylias

+3

@assylias Đúng nhưng ví dụ làm việc của OP cũng đánh giá đến ngày đầu tiên của tháng. – bowmore

+0

@Tunaki, hoặc: Ngày tháng = new SimpleDateFormat ("MMyy"). Parse ("1016"); LocalDate localDate = LocalDateTime.ofInstant (date.toInstant(), ZoneId.systemDefault()). ToLocalDate(); – user471011

Các vấn đề liên quan