Why does Java's Date.getYear() return 111 instead of 2011?

后端 未结 6 2013
抹茶落季
抹茶落季 2020-11-28 09:25

I am having a bit of trouble parsing a string date to a Date object. I use a DateFormat to parse the string, and when I print the value of the date

6条回答
  •  执念已碎
    2020-11-28 09:43

    President Evil nailed it, Date.getYear() returns a value that is the result of subtracting 1900 from the year that contains. And you you shouldn't use it.

    But quick fix for the code in the question is:

    Date dateFrom = null;
    
    String gDFString = g.getDateFrom();
    
    System.out.println(gDFString);
    
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    
    try {
        dateFrom = df.parse("04/12/2011");
    
        System.out.println(dateFrom);
    
        // Add 1900 to dateFrom.getYear() 
    
        System.out.println(dateFrom.getYear()+1900);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    

提交回复
热议问题