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"));
}
}
why this returns Sun Dec 05 00:00:00 GMT 28
I am expecting an exception.
The Javadoc for SimpleDateFormat
has this to say about repeated pattern letters:
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields
(Emphasis mine)
So for parsing , "yyyy-MM-dd"
is equivalent to "yMd"
.
With this pattern, "23-06-2015"
is parsed as year = 23, month = 6, dayOfMonth = 2015
.
By default, this gets resolved by starting at 1st June 0023, and counting 2015 days forward, taking you to 5th December 0028.
You can change this behaviour with SimpleDateFormat.setLenient(false)
-- with leniency disabled, it will throw an exception for out-of-range numbers. This is properly documented in Calendar.setLenient()
Note, for new code in Java 8, it's a good idea to avoid the old Date
and Calendar
classes. Use LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter)
if you can.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.