java.util.Date and getYear()

java.util.Date and getYear()

Asked on January 2, 2019 in Java.
Add Comment


  • 5 Answer(s)

    With the help of JavaDoc, this code should helps.

    @Deprecated
    public int getYear()
    

    Deprecated is one that programmers are discouraged from using, typically because it is dangerous, in JDK version 1.1 it was replaced by Calendar.get(Calendar.YEAR) – 1900.

    It yields that value is, from the year that contains subtract by 1900  or starts with the immediate in time represented by this as interpreted in the local time zone Date object.

    The output is here:   represented by this date, the year should be minus 1900.

    For more reference : Calendar

    So the output is 112, so try to use javadoc or javatime.

    Answered on January 2, 2019.
    Add Comment

    By try this code, one can know according to the javadoc, how to use java.util.Date, java.util.Calendar and java.util.GregorianCalendar .

    //Initialize your Date however you like it.
    Date date = new Date();
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    int year = calendar.get(Calendar.YEAR);
    //Add one to month {0 - 11}
    int month = calendar.get(Calendar.MONTH) + 1;
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    
    Answered on January 2, 2019.
    Add Comment

    Use this snippet in the actual code,

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = format.parse(datetime);
    SimpleDateFormat df = new SimpleDateFormat("yyyy");
    year = df.format(date);
    
    Answered on January 2, 2019.
    Add Comment

    The java documentation suggests to make use of Calendar class instead of this deprecated way Here is the sample code to set up the calendar object

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());

    Here is the sample code to get the year, month, etc.

    System.out.println(calendar.get(Calendar.YEAR));
    System.out.println(calendar.get(Calendar.MONTH));

    Calendar also has support for many other useful information like, TIME, DAY_OF_MONTH, etc. Here the documentation listing all of them Please note that the month are 0 based. January is 0th month.

    Answered on January 16, 2019.
    Add Comment

    Java 8 LocalDate class is another option to get the year from a java.util.Date,

    int year = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date)).getYear();

    Another option is,

    int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
    Answered on January 16, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.