簡體   English   中英

為什么SimpleDateFormat不會為無效格式拋出異常?

[英]Why SimpleDateFormat does not throw exception for invalid format?

import java.text.ParseException;

public class Hello {

    public static void main(String[] args) throws ParseException {
        System.out.println(new java.text.SimpleDateFormat("yyyy-MM-dd").parse("23-06-2015"));
    }
}

為什么這會返回Sun Dec 05 00:00:00 GMT 28我期待一個例外。

SimpleDateFormat的Javadoc有關於重復模式字母的說法:

數字:對於格式化,模式字母的數量是最小位數,較短的數字是零填充到此數量。 對於解析,除非需要分隔兩個相鄰字段,否則將忽略模式字母的數量

(強調我的)

因此, 對於解析"yyyy-MM-dd"相當於"yMd"

使用此模式, "23-06-2015"被解析為year = 23, month = 6, dayOfMonth = 2015

默認情況下,從0023年6月1日開始計算,並計算2015年前的日期,將您帶到0028年12月5日。

您可以使用SimpleDateFormat.setLenient(false)更改此行為 - 禁用lenalent時,它將為超出范圍的數字引發異常。 這在Calendar.setLenient()有適當的記錄


請注意,對於Java 8中的新代碼,避免使用舊的DateCalendar類是個好主意。 如果可以LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter)請使用LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM