Did this blog help you solve a problem? Tip me with Bitcoins at: 17dQktcAmU4urXz7tGk2sbuiCqykm3WLs6

Wednesday, April 20, 2011

Get Year from Date Object in Java

To get the year from a java.util.Date object, we can use the java.text.SimpleDateFormat class. First, create a Date object. Next, create a SimpleDateFormat instance using the getDateInstance() method, passing the String "yyyy" as the argument. Finally, get the year as a String using the format() method passing in the java.util.Date object.

Get Year from Date in Java - Example Code

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

//
// The following example code demonstrates how to
// print out the Year from a Date object.
//
public class GetYearFromDate {

    public static void main(String[] args) {

        Date now = new Date();
        SimpleDateFormat simpleDateformat = new SimpleDateFormat("yyyy");
        System.out.println(simpleDateformat.format(now));

    }
}

Here is the output of the example code:
2011

No comments: