Calendar类和GregorianCalendar类

java.util.Calendar 和它的一个具体子类,java.util.GregorianCalendar

Calendar 类

我们现在已经能够格式化并创建一个日期对象了, 但是我们如何才能设置和获取日期数据的特定部分呢, 比如说小时, 日, 或者分钟? 我们又如何在日期的这些部分加上或者减去值呢? 答案是使用Calendar 类. 就如我们前面提到的那样, Calendar 类中的方法替代了Date 类中被人唾骂的方法.

假设你想要设置, 获取, 和操纵一个日期对象的各个部分, 比方一个月的一天或者是一个星期的一天. 为了演示这个过程, 我们将使用具体的子类 java.util.GregorianCalendar. 考虑下面的例子, 它计算得到下面的第十个星期五是13号.

以下是引用片段:
import java.util.GregorianCalendar;
import java.util.Date;
import java.text.DateFormat;
public class DateExample5 {
public static void main(String[] args) {
DateFormat dateFormat =
DateFormat.getDateInstance(DateFormat.FULL);
// Create our Gregorian Calendar.
GregorianCalendar cal = new GregorianCalendar();
// Set the date and time of our calendar
// to the system's date and time
cal.setTime(new Date());
System.out.println("System Date: " +
dateFormat.format(cal.getTime()));
// Set the day of week to FRIDAY
cal.set(GregorianCalendar.DAY_OF_WEEK,
GregorianCalendar.FRIDAY);
System.out.println("After Setting Day of Week to Friday: " +
dateFormat.format(cal.getTime()));
int friday13Counter = 0;
while (friday13Counter <= 10) {
// Go to the next Friday by adding 7 days.
cal.add(GregorianCalendar.DAY_OF_MONTH, 7);
// If the day of month is 13 we have
// another Friday the 13th.
if (cal.get(GregorianCalendar.DAY_OF_MONTH) == 13) {
friday13Counter++;
System.out.println(dateFormat.format(cal.getTime()));
}
}
}
}

在这个例子中我们作了有趣的函数调用:

cal.set(GregorianCalendar.DAY_OF_WEEK,
GregorianCalendar.FRIDAY);
和:
cal.add(GregorianCalendar.DAY_OF_MONTH, 7);

set 方法能够让我们通过简单的设置星期中的哪一天这个域来将我们的时间调整为星期五. 注意到这里我们使用了常量 DAY_OF_WEEK 和 FRIDAY来增强代码的可读性. add 方法让我们能够在日期上加上数值. 润年的所有复杂的计算都由这个方法自动处理.


如果给你带来帮助,欢迎微信或支付宝扫一扫,赞一下。