Easy Tutorial
❮ File Compare Data Swap ❯

Java Example - Getting Year, Month, etc.

Java Examples

The following example demonstrates how to use the Calendar class to output the year, month, etc.:

Main.java File

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        int dow = cal.get(Calendar.DAY_OF_WEEK);
        int dom = cal.get(Calendar.DAY_OF_MONTH);
        int doy = cal.get(Calendar.DAY_OF_YEAR);

        System.out.println("Current Time: " + cal.getTime());
        System.out.println("Date: " + day);
        System.out.println("Month: " + month);
        System.out.println("Year: " + year);
        System.out.println("Day of the Week: " + dow);  // Sunday is the first day of the week and outputs as 1, Monday as 2, and so on
        System.out.println("Day of the Month: " + dom);
        System.out.println("Day of the Year: " + doy);
    }
}

The above code outputs the following result:

Current Time: Fri Mar 27 21:44:15 CST 2015
Date: 27
Month: 3
Year: 2015
Day of the Week: 6
Day of the Month: 27
Day of the Year: 86

Java Examples

❮ File Compare Data Swap ❯