分享

java获取当月的第一天或最后一天

 路人甲Java 2021-06-23

方式共有两种,使用java.util.Calendar日历类实现

第一种:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);//获得本月第一天calendar.add(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
String firstDay = sdf.format(calendar.getTime());
System.out.println("firstDay:"+ firstDay);//获得本月最后一天calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
String lastDay = sdf.format(calendar.getTime());

第二种:

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
cal.roll(Calendar.DAY_OF_MONTH, -1);
System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));

参考文章:https://www.cnblogs.com/dongming-03/p/5628947.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多