Java中操作日期

来源:互联网 发布:mac双系统开机切换 编辑:程序博客网 时间:2024/04/29 13:54

    通过增大和减小日期值或部分日期值。有两种方法可以让您做到这一点:

  • add()
  • roll()

第一种方法允许将一些时间量添加到 Date 的特定区段中(或者通过添加负时间量来减少时间量)。做到这一点需要以增加某一特定区段为基础来相应地调整 Date 的其他所有区段。例如,假定日期是从 2005 年 11 月 15 日开始的,并且要将表示天数的字段增加到 20。那么我们可以使用以下代码:


Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.MONTH, 10);
calendar.set(Calendar.DAY_OF_MONTH, 15);
calendar.set(Calendar.YEAR, 2005);
formatter = new SimpleDateFormat("MMM dd, yyyy");
System.out.println("Before: " + formatter.format(calendar.getTime()));

calendar.add(Calendar.DAY_OF_MONTH, 20);
System.out.println("After: " + formatter.format(calendar.getTime()));

结果看起来如下所示:


Before: Nov 15, 2005
After: Dec 05, 2005

相当简单。但是调整 Date 是什么意思呢?它意味着可以通过给定时间量来增加或减小特定日期/时间区段的值,而不会影响其他区段。例如,我们可以将日期从 11 月份调整到 12 月份:


Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.MONTH, 10);
calendar.set(Calendar.DAY_OF_MONTH, 15);
calendar.set(Calendar.YEAR, 2005);
formatter = new SimpleDateFormat("MMM dd, yyyy");
System.out.println("Before: " + formatter.format(calendar.getTime()));
calendar.roll(Calendar.MONTH, true);
System.out.println("After: " + formatter.format(calendar.getTime()));

注意,月份向上调整(或增加)了 1。有两种格式的 roll()

  • roll(int field, boolean up)
  • roll(int field, int amount)

我们采用第一种格式。要使用这种格式增加某一字段值,则需要将 false 作为第二个参数传递。该方法的第二种格式允许指定增加或减少的量。如果调整操作创建了一个无效值(例如,09/31/2005),那么这些方法会根据日期、时间等区段的有效最大和最小值来相应地调整其他区段。可以用正值向前调整日期,同时也可以使用负值向后调整日期。

试着预测调整操作将做什么,以及您可以做什么,这样做很好,但是通常反复试验并找出错误才是最好的方法。有时您的猜测是正确的,但是有时则必须做试验,以查看怎样才能产生正确的结果。

 
原创粉丝点击