Bài tập xử lý ngày tháng trong java

/*Phương thức roll[] dùng để hiệu các giá trị giữa các đối tượng Calendar, bạn phải chỉ định trường của đối tượng Calendar nào ảnh hưởng bởi thao tác này.

[Calendar.YEAR, Calendar.MONTH, Calendar.DATE].

Ghi chú: Để hiệu 2 ngày bạn chỉ đơn giản chỉ định false trong tham số của phương thức roll[]

Theo JDK:

/**

* Adds or subtracts [up/down] a single unit of time on the given time

* field without changing larger fields. For example, to roll the current

* date up by one day, you can achieve it by calling:

*

roll[Calendar.DATE, true].

* When rolling on the year or Calendar.YEAR field, it will roll the year

* value in the range between 1 and the value returned by calling

* getMaximum[Calendar.YEAR].

* When rolling on the month or Calendar.MONTH field, other fields like

* date might conflict and, need to be changed. For instance,

* rolling the month on the date 01/31/96 will result in 02/29/96.

* When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will

* roll the hour value in the range between 0 and 23, which is zero-based.

*

* @param field the time field.

* @param up indicates if the value of the specified time field is to be

* rolled up or rolled down. Use true if rolling up, false otherwise.

* @see Calendar#add[int,int]

* @see Calendar#set[int,int]

*/

*/

public static void subToDate[]{

System.out.println[“2. Subtract to a date Operation\n”];

SimpleDateFormat sdf = new SimpleDateFormat[DATE_FORMAT];

Calendar c1 = Calendar.getInstance[];

c1.set[2008, 02 , 20];

System.out.println[“Date is : ” + sdf.format[c1.getTime[]]];

// roll down, substract 1 month

c1.roll[Calendar.MONTH, false];

System.out.println[“Date roll down 1 month : ” + sdf.format[c1.getTime[]]];

c1.set[2008, 02 , 20];

System.out.println[“Date is : ” + sdf.format[c1.getTime[]]];

c1.add[Calendar.MONTH, –1];

// substract 1 month

System.out.println[“Date minus 1 month : ” + sdf.format[c1.getTime[]]];

System.out.println[];

System.out.println[“——————————————————-“];

}

Chủ Đề