要使用Calendar类,请导入以下程序包。
import java.util.Calendar;
创建一个Calendar类对象。
Calendar cal = Calendar.getInstance();
现在,使用以下字段获取月份和年份的星期。
Calendar.WEEK_OF_MONTH Calendar.WEEK_OF_YEAR
以下是一个示例。
import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); // current date and time System.out.println(cal.getTime().toString()); // date information System.out.println("\nDate Information.........."); System.out.println("Year = " + cal.get(Calendar.YEAR)); System.out.println("Month = " + (cal.get(Calendar.MONTH) + 1)); System.out.println("Date = " + cal.get(Calendar.DATE)); // week System.out.println("Week of month = " + cal.get(Calendar.WEEK_OF_MONTH)); System.out.println("Week of year = " + cal.get(Calendar.WEEK_OF_YEAR)); // time information System.out.println("\nTime Information.........."); System.out.println("Hour (24 hour format) : " + cal.get(Calendar.HOUR_OF_DAY)); System.out.println("Hour (12 hour format) : " + cal.get(Calendar.HOUR)); System.out.println("Minute : " + cal.get(Calendar.MINUTE)); System.out.println("Second : " + cal.get(Calendar.SECOND)); System.out.println("Millisecond : " + cal.get(Calendar.MILLISECOND)); } }
输出结果
Mon Nov 19 14:28:46 UTC 2018 Date Information.......... Year = 2018 Month = 11 Date = 19 Week of month = 4 Week of year = 47 Time Information.......... Hour (24 hour format) : 14 Hour (12 hour format) : 2 Minute : 28 Second : 46 Millisecond : 464