Java Examples - Get Year, Month, etc.

Java 实例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 is output 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 output of running the above code is:

当期时间: Fri Mar 27 21:44:15 CST 2015
日期: 27
月份: 3
年份: 2015
一周的第几天: 6
一月中的第几天: 27
一年的第几天: 86

Java 实例Java Examples

Other Extensions