java后台返回当前日期前30天的数据并排序

项目中遇到需要给前端返回30天的血糖数据,数据库中,只有当用户输入血糖才会有数据,所以后台需要把没有的数据补0。
思路是先使用工具类WeekUtil 获取当前日期的前30天日期,放在map中,键为时间,值为0,然后查出30天内的数据库的血糖记录list,遍历list,将数据放入到map中,然后将map中数据放入vo集合中,并按照对象属性createTime进行排序。
weekUtils代码如下:

   package com.wellness.platfront.common.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取当天所在的一周的日期工具类
 * 
 */
public class WeekUtil {

    private static WeekUtil instance = new WeekUtil();
    private static SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd");  

    private WeekUtil(){}

    public static WeekUtil getInstance(){
        return instance;
    }

    /**
     * 根据传入时间获取 该时间所在的一周的日期
     * @param date 传入时间参数
     * @return
     */
    public static Map<String,Date> weekDateOfToday(Date date){
        Map<String,Date> weekMap = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);


        try {
            //周一
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            Date mon = calendar.getTime();

            //周二
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
            Date tues = calendar.getTime();

            //周三
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
            Date wen = calendar.getTime();

            //周四
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
            Date thur = calendar.getTime();

            //周五
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
            Date fri = calendar.getTime();

            //周六
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
            String satday = simpleDateFormat.format(calendar.getTime());
            Date sat = simpleDateFormat.parse(satday);

            //周天
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
            String sunday = simpleDateFormat.format(calendar.getTime());
            Date sun = simpleDateFormat.parse(sunday);
            weekMap.put("monday",mon);
            weekMap.put("tuesday",tues);
            weekMap.put("wednesday",wen);
            weekMap.put("thursday",thur);
            weekMap.put("friday",fri);
            weekMap.put("saturday",sat);
            weekMap.put("sunday",sun);
        }catch (Exception e){
            e.printStackTrace();
        }




        return weekMap;
    }

    /**
     * 根据传入时间获取 该时间所在的一周的日期
     * @param date 传入时间参数
     * @return
     */
    public static List<String> weekDayOfToday(Date date){
        List<String> weekList = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d");
        //周一
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        String mon = simpleDateFormat.format(calendar.getTime());


        //周二
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
        String tues = simpleDateFormat.format(calendar.getTime());

        //周三
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
        String wen = simpleDateFormat.format(calendar.getTime());

        //周四
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
        String thur = simpleDateFormat.format(calendar.getTime());

        //周五
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        String fri = simpleDateFormat.format(calendar.getTime());

        //周六
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        String sat = simpleDateFormat.format(calendar.getTime());

        //周天
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        String sun = simpleDateFormat.format(calendar.getTime());

        weekList.add(sun);
        weekList.add(mon);
        weekList.add(tues);
        weekList.add(wen);
        weekList.add(thur);
        weekList.add(fri);
        weekList.add(sat);

        return weekList;
    }

    /**
     * 获取当前输入时间所在月份的所有 天
     * @return
     */
    public static List<String> getDaysOfNowMonth(){
        List<String> monthDayList = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("d");
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        //获取当月最后一天
        Integer last = Integer.parseInt(format.format(ca.getTime()));
        for (int i = 1;i <= last;i++ ){
            monthDayList.add(i+"");
        }
        return monthDayList;
    }

    /**
     * 获取当前输入时间所在月份的所有日期
     * @return
     */
    public static Map<String,Date> getDateOfNowMonth(){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Map<String,Date> dateMap = new HashMap<>();
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));


        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);

        try {
            //第一天
            String firstDateStr = simpleDateFormat.format(c.getTime());
            Date firstDate = simpleDateFormat.parse(firstDateStr);
            //最后一天
            String lastDateStr = simpleDateFormat.format(ca.getTime());
            Date lastDate = simpleDateFormat.parse(lastDateStr);

            dateMap.put("firstDay",firstDate);
            dateMap.put("lastDay",lastDate);
        }catch (Exception e){
            e.printStackTrace();
        }

        return dateMap;
    }

    /**
     * 获取今日前number日的日期
     * @param number
     * @return
     */
    public static Date getDayFromToday(Integer number){
        try {

            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(c.DAY_OF_YEAR, -number);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String date = simpleDateFormat.format(c.getTime());
            return simpleDateFormat.parse(date);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取今日的日期
     * @return
     */
    public static Date getDayToday(){
        try {
            Date date = new Date();
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(Calendar.DAY_OF_MONTH, 1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = simpleDateFormat.format(c.getTime());
            return simpleDateFormat.parse(dateStr);
        }catch (Exception e){
            e.printStackTrace();
        }
            return null;
    }

    public static List<String> getMonthDayList(){
        List<String> dayList = new ArrayList<>();
        dayList.add("7");
        dayList.add("14");
        dayList.add("21");
        dayList.add("28");
        return dayList;
    }
    /**
     * 返回两个时间之间相差多少天
     * @param now
     * @param past
     * @return
     */
    public static Integer dayNumberBetweenToDate(Date now , Date past){
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String pastString = simpleDateFormat.format(past);
            Date pastDate = simpleDateFormat.parse(pastString);
            return (int)(((now.getTime() - pastDate.getTime() )/ (1000 * 3600 * 24)));
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前日期前30天的日期(用于返回30天内血糖和血压)
     */
    public static Map<String, String> getDayMap(){
        try {
            Calendar calc =Calendar.getInstance();    
            Map<String, String> bloodMap = new HashMap<String, String>();
             for(int i=0;i<30;i++){  
                   calc.setTime(new Date());    
                   calc.add(calc.DATE, -i);    
                   Date minDate = calc.getTime();    
                   bloodMap.put(sdf.format(minDate), "0");
                  }  
             return bloodMap;
        } catch (Exception e) {
              e.printStackTrace();
        }
        return null;
    } 
}

BloodGlucoseVo为返回给前端的vo:

package com.wellness.platfront.entity.healthCenter.vo;

/**
 * 血糖的vo
 * @author 
 * @since 2017/09/26
 */
public class BloodGlucoseVo {
    /**
     * 血糖值
     */
    private String value;
    /**
     * 创建时间
     */
    private String createTime;
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public String getCreateTime() {
        return createTime;
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

}

service实现类中的方法:

package com.wellness.platfront.business.healthCenter.service.impl;

import com.wellness.platfront.business.healthCenter.service.BloodGlucoseService;
import com.wellness.platfront.business.healthCenter.validate.BloodValidate;
import com.wellness.platfront.business.member.service.MemberService;
import com.wellness.platfront.common.core.dao.primitive.HibernateDao;
import com.wellness.platfront.common.core.service.impl.BasicServiceImpl;
import com.wellness.platfront.common.exception.BasicRuntimeException;
import com.wellness.platfront.common.util.WeekUtil;
import com.wellness.platfront.entity.healthCenter.BloodGlucose;
import com.wellness.platfront.entity.healthCenter.vo.BloodGlucoseVo;
import com.wellness.platfront.entity.member.Member;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javassist.expr.NewArray;

import javax.annotation.Resource;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 
 * @version 创建时间:2017年5月31日
 * 血糖接口实现类
 */
@Service("bloodGlucoseService")
@Transactional
public class BloodGlucoseServiceImpl extends BasicServiceImpl<BloodGlucose, Integer>
        implements BloodGlucoseService {
    @Resource
    private SessionFactory sessionFactory;
    @Resource
    private MemberService memberService;
    Calendar calendar = Calendar.getInstance();
    private HibernateDao<BloodGlucose, Integer> dao = new HibernateDao<>(sessionFactory,
            BloodGlucose.class);
    private SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");

    /**
     * 查询最近30天的血糖记录
     */
    @Override
    public List<BloodGlucoseVo> getMonthBloodSugar(Integer memberId) {
         try {
         //定义排序规则
    Comparator mycmp = ComparableComparator.getInstance();
         //reversedComparator 为倒序排序,默认为正序,
             mycmp = ComparatorUtils.reversedComparator(mycmp);
    //如果要自定义的排序规则,需在bean的属性后加上,如果默认则不用加,"createTime"为集合对象中的属性
             BeanComparator bc = new BeanComparator("createTime",mycmp);
             List<BloodGlucoseVo> list = new ArrayList<>();
                calendar.setTime(new Date());
                calendar.add(Calendar.DATE, -30);
                Date firstDate = calendar.getTime();
                Criteria criteria = dao.createCriteria();
                criteria.add(Restrictions.eq("member.memberId", memberId));
                criteria.add(Restrictions.ge("createTime", firstDate));
                criteria.add(Restrictions.le("createTime", new Date()));
                criteria.addOrder(Order.desc("createTime"));
                List<BloodGlucose> bloodGlucoses = criteria.list();
                //获取30天的日期集合
                Map<String, String> dayMap = WeekUtil.getDayMap();
                if (bloodGlucoses.size()>0) {
                    BloodGlucoseVo bloodGlucoseVo;
                    //将数据库查询的list集合数据放入map中
                    for (int j = 0; j < bloodGlucoses.size(); j++) {
                        //需要将时间格式化成与map返回的时间一样格式  yyyy-MM-dd 并将时间和血糖值放入map中覆盖原来的value
                        dayMap.put(dateFormat.format(bloodGlucoses.get(j).getCreateTime()), bloodGlucoses.get(j).getValue());
                    }
                    //将map中的数据放入对应list中
                    for (String day : dayMap.keySet()) {
                        bloodGlucoseVo = new BloodGlucoseVo();
                        bloodGlucoseVo.setValue(dayMap.get(day));
                        bloodGlucoseVo.setCreateTime(day);
                        list.add(bloodGlucoseVo);
                        bloodGlucoseVo = null;
                    }
                    //将返回数据的list按照时间排序
                    Collections.sort(list, bc);
                }

                return list;
            } catch (Exception e) {
                log.error(e.getMessage());
                throw new BasicRuntimeException(this, "获取最近三十天的血糖记录异常" + e.getMessage());
            }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值