package com.test.packager; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; public class Test { private static String firstDay; private static String lastDay; 10 public static void main(String[] args) { 11 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 12 13 //获取前月的第一天 14 Calendar cal_1=Calendar.getInstance();//获取当前日期 15 cal_1.add(Calendar.MONTH, -1); 16 cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 17 firstDay = format.format(cal_1.getTime()); 18 System.out.println("-----1------firstDay:"+firstDay); 19 //获取前月的最后一天 20 Calendar cale = Calendar.getInstance(); 21 cale.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天 22 lastDay = format.format(cale.getTime()); 23 System.out.println("-----2------lastDay:"+lastDay); 24 25 26 //获取当前月第一天: 27 Calendar c = Calendar.getInstance(); 28 c.add(Calendar.MONTH, 0); 29 c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 30 String first = format.format(c.getTime()); 31 System.out.println("===============first:"+first); 32 33 //获取当前月最后一天 34 Calendar ca = Calendar.getInstance(); 35 ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); 36 String last = format.format(ca.getTime()); 37 System.out.println("===============last:"+last); 38 39 } 40 /** 41 * 字符串的日期格式的计算 42 */ 43 public static int daysBetween(String smdate,String bdate) throws ParseException{ 44 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 45 Calendar cal = Calendar.getInstance(); 46 cal.setTime(sdf.parse(smdate)); 47 long time1 = cal.getTimeInMillis(); 48 cal.setTime(sdf.parse(bdate)); 49 long time2 = cal.getTimeInMillis(); 50 long between_days=(time2-time1)/(1000*3600*24); 51 return Integer.parseInt(String.valueOf(between_days)); 52 } 53 }
java获取当前月第一天和最后一天,上个月第一天和最后一天
最新推荐文章于 2024-07-20 03:04:13 发布