日期常用操作类DateUtil

一、给定yyyy-MM-dd hh:mm:ss格式的字符串,返回Date.

复制代码
    public Date convertStr2Date(String dateString) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date date = sdf.parse(dateString);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
复制代码

二、取得指定日期的前几分钟或者后几分钟的日期,返回"yyyy-MM-dd hh:mm:ss"形式的字符串。

复制代码
    public String arroundIntervalMinute(Date inDate,int interval) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Calendar calender = Calendar.getInstance();
        calender.setTime(inDate);
        calender.add(Calendar.MINUTE, interval);
        Date endDateTime = calender.getTime();
        return sdf.format(endDateTime);
    }
复制代码

三、取得指定日期的前几天或者后几天的日期,返回"yyyy-MM-dd 00:00:00"形式的字符串.

复制代码
public String arroundIntervalDay(Date inDate, int interval) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calender = Calendar.getInstance();
        calender.setTime(inDate);
        calender.add(Calendar.DATE, interval);
        Date endDateTime = calender.getTime();
        String endDate = sdf.format(endDateTime);
        endDate += " 00:00:00";
        return endDate;
    }
复制代码

PS:返回00:00:00是我的需求,为了统计每一天的数据.

interval为1时,为输入天数的后一天,为-1时为输入天数的前一天

posted @ 2023-01-04 14:53  阿风小子  阅读(44)  评论(0)    收藏  举报