概述
The <code>Calendar</code> class is an abstract class that provides methods for converting between a specific instant in time and a set of {@link #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>, <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for manipulating the calendar fields, such as getting the date of the next week.
An instant in time can be represented by a millisecond value that is an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970 00:00:00.000 GMT (Gregorian).
Calendar是一个抽象类;
作用: time 与 Calendar的YEAR、MONTH等的转换 以及 用于操作Calendar字段的方法;
time用ms表示,该值是一个相对于标准时间(1970 年 1 月 1 日 00:00:00.000 GMT)的偏移量;
The class also provides additional fields and methods for implementing a concrete calendar system outside the package.
Those fields and methods are defined as <code>protected</code>.
Calendar也提供了额外的字段&方法,用于在包外实现calendar;
Like other locale-sensitive classes, <code>Calendar</code> provides a class method, <code>getInstance</code>, for getting a generally useful object of this type.
<code>Calendar</code>'s <code>getInstance</code> method returns a <code>Calendar</code> object whose calendar fields have been initialized with the current date and time:
Calendar提供了getInstance方法,用于获取Calendar(字段已被当前time初始化);
public abstract class Calendar implements Serializable, Cloneable, Comparable<java.util.Calendar> { protected long time; public int get(int field) { complete(); return internalGet(field); } public static Calendar getInstance() { return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT)); } public final Date getTime() { return new Date(getTimeInMillis()); } public long getTimeInMillis() { if (!isTimeSet) { updateTime(); } return time; } }
方法
get
time与Calendar的YEAR、MONTH等的转换
Calendar calendar = Calendar.getInstance(); int i = calendar.get(Calendar.YEAR); int i1 = calendar.get(Calendar.MONTH); int i2 = calendar.get(Calendar.DATE); int i3 = calendar.get(Calendar.HOUR); int i4 = calendar.get(Calendar.MINUTE); int i5 = calendar.get(Calendar.SECOND); System.out.println(i + "-" + i1+ "-" + i2+ " " + i3+ ":" + i4+ ":" + i5); // 2023-11-20 10:52:47 int i6 = calendar.get(Calendar.WEEK_OF_YEAR); int i7 = calendar.get(Calendar.DAY_OF_YEAR); System.out.println(i6 + " " + i7); int i8 = calendar.get(Calendar.WEEK_OF_MONTH); int i9 = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(i8 + " " + i9); int i10 = calendar.get(Calendar.DAY_OF_WEEK); int i11 = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);
set
为 年、月、日、时、分、秒 设置指定的值;
Calendar calendar1 = Calendar.getInstance(); calendar1.set(2001, Calendar.OCTOBER,23,12,23,54); Date time = calendar1.getTime(); System.out.println(time); // Tue Oct 23 12:23:54 CST 2001 String format1 = DateFormat.getDateTimeInstance().format(time); System.out.println(format1); // 2001-10-23 12:23:54