时间工具类,根据本月时间获取上月一号零点零时零分零秒

这次项目中,遇到一个需求,只查看当前月份和上个月的数据。本月时间容易,new Data() 就可以了,但是获取上个月时间,并且还得是上个月1号零时就有点麻烦了。

在此,写个工具类来获取这些时间,以方便后期使用。

public class ObtainTime {

public static String lastMonth(){

//处理时间,格式化时间为固定格式

        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar nowTime=Calendar.getInstance();//获取当前日期

        nowTime.add(Calendar.MONTH, -1);//当前月份减1,为上一个月

        nowTime.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天

        nowTime.set(Calendar.HOUR_OF_DAY, 0);//将小时至零

        nowTime.set(Calendar.MINUTE, 0);//将分钟至零

        nowTime.set(Calendar.SECOND, 0);//将秒至零

        nowTime.set(Calendar.MILLISECOND, 0);//将毫秒至零

        String lastMonth = sdf.format(nowTime.getTime());

        return lastMonth;
    }
}

打印效果:
效果图
至于为什么我写的返回是Sting类型,因为返回是Data的话,接收的时候需要再次格式化才能到sql语句里面使用,不然还是英文时间格式。

谢谢观看,转载需注明出处哦~

猜你喜欢

转载自blog.csdn.net/weixin_43829443/article/details/91520731
今日推荐