Java实现获取前、后N天日期的函数分享2

来源:互联网 发布:印度尼西亚华人知乎 编辑:程序博客网 时间:2024/06/07 14:19
两日期之间的旬差
for (int j = 1; j <= 5; j++) {//取得最近5个旬度的时间,从当前旬的上一旬开始往前推算Date curDate = new Date();int a = -1;//设置已循环的次数(因为要排除掉当前旬,所以从-1开始,否则从0开始)if(curDate.getDate()==1 || curDate.getDate()==11 || curDate.getDate()==21){//如果当前时间已经是1日、11日或21日,则视为已经排除掉当前旬a++;}while(true){//从当前日期开始,逐天相减,每遇到1日、11日、21日,循环次数+1(视为已计算该旬度),curDate.setDate(curDate.getDate()-1);if(curDate.getDate()==1 || curDate.getDate()==11 || curDate.getDate()==21){//如果当前时间已经是1日、11日或21日,则视为已经排除掉当前旬a++;if(a==j){//如果找到了目标旬度,则跳出循环break;}}}String sdfXdStr = "";if(curDate.getDate()==1){sdfXdStr = "yyyy年M月上旬";}else if(curDate.getDate()==11){sdfXdStr = "yyyy年M月中旬";}else if(curDate.getDate()==21){sdfXdStr = "yyyy年M月下旬";}SimpleDateFormat sdf = new SimpleDateFormat(sdfXdStr);System.out.println(sdf.format(curDate));}我的系统时间是2014年9月5日,最后输出结果是:2014年8月下旬2014年8月中旬2014年8月上旬2014年7月下旬2014年7月中旬




Java实现获取前、后N天日期的函数分享

public Date getdate(int i) // //获取前后日期 i为正数 向后推迟i天,负数时向前提前i天 { Date dat = null; Calendar cd = Calendar.getInstance(); cd.add(Calendar.DATE, i); dat = cd.getTime(); SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Timestamp date = Timestamp.valueOf(dformat.format(dat)); return date; }


java获取当前年月

Calendar cal = Calendar.getInstance();int year = cal.get(Calendar.YEAR);int month = cal.get(Calendar.MONTH )+1;System.out.println(year + " 年 " + month + " 月");




原创粉丝点击