Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

java - SimpleDateFormat problems with 2 year date

I'm trying to understand two things:

  1. Why doesn't the following code throw an exception (since the SimpleDateFormat is not lenient)
  2. It doesn't throw an exception, but why is it parsing the year as 0013 (instead of using the rules here the +80:-20 years from today rule)

Here's the code

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TestDate {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        format.setLenient(false);
        Date date = format.parse("01/01/13"); // Since this only has a 2 digit year, I would expect an exception to be thrown

        System.out.println(date); // Prints Sun Jan 01 00:00:00 GMT 13

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        System.out.println(cal.get(Calendar.YEAR)); // Prints 13
    }
}

If it makes a difference, I'm using java 1.6.0_38-b05 on Ubuntu

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Question 1. This is a partial duplicate of Why Does Java's SimpleDateFormat parse this. The second answer on the question answers this nicely. The crux of it is this:

Number: For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields. Year: During parsing, only strings consisting of exactly two digits […] will be parsed into the default century. Any other numeric string, such as a one digit string, a three or more digit string, or a two digit string that isn't all digits (for example, "-1"), is interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the same pattern

Question 2. Look carefully: your input format is not the same as the format that you are passing to the function.

new SimpleDateFormat("dd/MM/yyyy");

vs.

format.parse("01/01/13");

Either parse to 01/01/2013 or use the date forat 'dd/MM/yy'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...