Board logo

标题: java中取得当月最后一天的四种方法 [打印本页]

作者: qingqing3721    时间: 2011-8-19 02:44     标题: java中取得当月最后一天的四种方法

第一种,使用Calendar的roll方法,在限制某个日期字段不改变的方式下,改变其他日期字段的值。第二种,使用Calendar的getActualMaximum方法,取得指定日期字段的最大值。第三种,使用Calendar的set和add方法,从下个月的第一天计算得到当前月的最后一天。第四种,循环使用Calendar的add方法,加到本月的最后一天。以上四种方法如下示例:import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class DateTime {  public static void main(String[] args) throws ParseException {  DateTime dt = new DateTime();    Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14");  date = dt.lastDayOfMonth(date);  System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date));    date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14");  date = dt.lastDayOfMonth2(date);  System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date));    date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14");  date = dt.lastDayOfMonth3(date);  System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date));    date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14");  date = dt.lastDayOfMonth4(date);  System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date)); } public Date lastDayOfMonth(Date date) {  Calendar cal = Calendar.getInstance();  cal.setTime(date);  cal.set(Calendar.DAY_OF_MONTH, 1);  cal.roll(Calendar.DAY_OF_MONTH, -1);  return cal.getTime(); }
public Date lastDayOfMonth2(Date date) {  Calendar cal = Calendar.getInstance();  cal.setTime(date);  int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH);  cal.set(Calendar.DAY_OF_MONTH, value);  return cal.getTime(); } public Date lastDayOfMonth3(Date date) {  Calendar cal = Calendar.getInstance();  cal.setTime(date);  cal.set(Calendar.DAY_OF_MONTH, 1);  cal.add(Calendar.1MONTH, 1);  cal.add(Calendar.DATE, -1);  return cal.getTime(); }  public Date lastDayOfMonth4(Date date) {  Calendar cal = Calendar.getInstance();  cal.setTime(date);  do {   cal.add(Calendar.DATE, 1);  }  while (cal.get(Calendar.DATE) != 1);  cal.add(Calendar.DATE, -1);  return cal.getTime(); } }输出日期:2008-02-14输出结果:2008-02-292008-02-292008-02-292008-02-29

原文链接:kin111.blog.51cto/738881/221672




欢迎光临 编程开发论坛 (http://bbs.lihuasoft.net/) Powered by Discuz! 6.0.0