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

后端 未结 6 2018
抹茶落季
抹茶落季 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:37

    Those methods have been deprecated. Instead, use the Calendar class.


    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    
    public final class DateParseDemo {
        public static void main(String[] args){
             final DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
             final Calendar c = Calendar.getInstance();
             try {
                 c.setTime(df.parse("04/12/2011"));
                 System.out.println("Year = " + c.get(Calendar.YEAR));
                 System.out.println("Month = " + (c.get(Calendar.MONTH)));
                 System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));
             } 
             catch (ParseException e) {
                 e.printStackTrace();
             }
        }
    }
    

    Output:

    Year = 2011
    Month = 3
    Day = 12
    

    And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,

    Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

提交回复
热议问题