您的位置:首页 > 编程语言 > Java开发

java一些比较实用的方法,持续更新中

2018-03-28 11:27 507 查看
1、将json格式的字符串转换成List
 List<PointBean> list = new GsonBuilder().create().fromJson(resultStr, new TypeToken<List<PointBean>>() {

        }.getType());

2、mongo查询时间段的语句
mongo视图中的语句写法:

db.getCollection('dishonesty_system_error').find({errorTime:{$gte:1481526000000,$lt:1481529600000}})  (其中errorTime的类型为Long类型)

程序中的代码:

public List<ContactPersonBean> findAllContactpersonByTime(String start, String end) {
        Query query = new Query(Criteria.where("createTime").gte(Long.valueOf(start)).lt(Long.valueOf(end)));
        return mongoTemplate.find(query, ContactPersonBean.class);

    }
3、日期格式的相互转换
  /**
     * 日期格式的转换(String类型转long)
     *
     * @param date
     * @return
     */
    private static long dateFormat(String date) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = null;
        try {
            date1 = df.parse(date);
        } catch (Exception e) {
            logger.info("parse error");
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        return cal.getTimeInMillis();
    }

    /**
     * 日期格式的转换(long类型转日期)
     */
    private static String formatData(Long timestap) {
        Date date = new Date(timestap);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sdf.format(date);

    }
private static Log logger = LogFactory.getLog(DateUtil.class);
    
    /**
     * 把时间转换为秒数
     * 
     * @param time
     * hh小时mm分ss秒 ,hh时mm分ss秒 , mm分ss秒 ,ss秒
     * hh小时mm分钟ss秒 ,hh时mm分钟ss秒,mm分钟ss秒 ,30
     * @return 秒
     */
    public static int convertTimeToSecond(String time)
    {
        Pattern p = Pattern.compile("\\d*");
        Matcher m = p.matcher(time);
        
        List<Integer> times = new ArrayList<Integer>();
        while (m.find())
        {
            if (StringUtils.isNotBlank(m.group()))
            {
                times.add(Integer.valueOf(m.group()));
            }
        }
        switch (times.size())
        {
            case 0:
                return 0;
            case 1:
                // ss
                return times.get(0);
            case 2:
                // mm:ss
                return times.get(0) * 60 + times.get(1);
            case 3:
                // hh:mm:ss
                return times.get(0) * 60 * 60 + times.get(1) * 60 + times.get(2);
            default:
                return 0;
        }
        
    }
    
    /**
     * 把时间转换为秒数
     * 
     * @param time 00:00:04
     * @return 秒
     */
    public static int convertNomorTimeToSecond(String time)
    {
        int second = 0;
        try
        {
            String[] times = time.split(":");
            if (times.length == 3)
            {
                second += Integer.parseInt(times[0]) * 60 * 60;
                second += Integer.parseInt(times[1]) * 60;
                second += Integer.parseInt(times[2]);
            }
            else if (times.length == 2)
            {
                second += Integer.parseInt(times[0]) * 60;
                second += Integer.parseInt(times[1]);
            }
            else if (times.length == 1)
            {
                second = Integer.parseInt(time);
            }
        }
        catch (Exception e)
        {
            logger.error("parse nomore time fail! the time is " + time, e);
        }
        return second;
    }
    
    /**
     * 日期增加几天
     * @param datestr 日期
     * @param step 增加的天数,负数为减少调试
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String addDay(String datestr, int step)
    {
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date = formatter.parse(datestr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DATE, step);
            return formatter.format(calendar.getTime());
        }
        catch (ParseException e)
        {
            logger.error("add day error!datestr=" + datestr + "step=" + step, e);
        }
        return null;
    }
    
    /**
     * 月份增加几天
     * @param datestr 日期
     * @param step 增加的天数,负数为减少调试
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String addMonth(String datestr, int step)
    {
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date = formatter.parse(datestr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MONTH, step);
            return formatter.format(calendar.getTime());
        }
        catch (ParseException e)
        {
            logger.error("add day error!datestr=" + datestr + "step=" + step, e);
        }
        return null;
    }
    
    /**
     * 判断日期是否是最近一周
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isCurWeek(String date)
    {
        try
        {
            String curDate = getCurYearMonthDate();
            String lastDate = addDay(curDate, -7);
            
            int result1 = date.compareTo(curDate);
            int result2 = date.compareTo(lastDate);
            if (result1 <= 0 && result2 >= 0)
            {
                return true;
            }
        }
        catch (Exception e)
        {
            logger.error("isCurWeek error!date=" + date, e);
        }
        return false;
    }
    
    /**
     * 判断日期是否是最近一月
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isCurMonth(String date)
    {
        try
        {
            String curDate = getCurYearMonthDate();
            String lastDate = addMonth(curDate, -1);
            
            int result1 = date.compareTo(curDate);
            int result2 = date.compareTo(lastDate);
            if (result1 <= 0 && result2 >= 0)
            {
                return true;
            }
        }
        catch (Exception e)
        {
            logger.error("isCurMonth error!date=" + date, e);
        }
        return false;
    }
    
    /**
     * 判断日期是否是
4000
最近三月
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isCurThreeMonth(String date)
    {
        try
        {
            String curDate = getCurYearMonthDate();
            String lastDate = addMonth(curDate, -3);
            
            int result1 = date.compareTo(curDate);
            int result2 = date.compareTo(lastDate);
            if (result1 <= 0 && result2 >= 0)
            {
                return true;
            }
        }
        catch (Exception e)
        {
            logger.error("isCurThreeMonth error!date=" + date, e);
        }
        return false;
    }
    
    /**
     * 传入的日期是否在2个时间之间
     * @param date 需要判断的时间 HH:mm:ss
     * @param startTime 
     * @param endTime
     * @return 之间返回true
     * @see [类、类#方法、类#成员]
     */
    public static boolean isBetwenTime(String date, String startTime, String endTime)
    {
        try
        {
            if (date.length() > 8)
            {
                date = date.substring(date.length() - 8, date.length());
            }
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            Calendar cal0 = Calendar.getInstance();
            cal0.setTime(formatter.parse(date));
            String date0 = formatter.format(cal0.getTime());
            int result1 = date0.compareTo(startTime);
            int result2 = date0.compareTo(endTime);
            
            if (result1 > 0 && result2 < 0)
                return true;
            else
                return false;
        }
        catch (Exception e)
        {
            logger.error("parse time fail! the time is " + date, e);
        }
        return false;
    }
    
    /**
     * 判断日期是否是凌晨
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isEarlyMorning(String date)
    {
        return isBetwenTime(date, "00:00:00", "05:00:00");
    }
    
    /**
     * 判断日期是否是上午
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isMorning(String date)
    {
        return isBetwenTime(date, "05:00:00", "12:00:00");
    }
    
    /**
     * 判断日期是否是下午
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isNoon(String date)
    {
        return isBetwenTime(date, "14:00:00", "18:00:00");
    }
    
    /**
     * 判断日期是否是晚上
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isAfternoon(String date)
    {
        return isBetwenTime(date, "18:00:00", "22:00:00");
    }
    
    /**
     * 判断日期是否是深夜
     * 
     * @param date
     *            HH:mm:ss
     * @return
     */
    public static boolean isNight(String date)
    {
        return isBetwenTime(date, "22:00:00", "23:59:59");
    }
    
    /**
     * 判断日期是否是周中
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isWeekday(String date)
    {
        try
        {
            Calendar cal = Calendar.getInstance();
            
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            
            cal.setTime(formatter.parse(date));
            int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (week == 1 || week == 2 || week == 3 || week == 4 || week == 5)
            {// 0代表周日,6代表周六
                return true;
            }
        }
        catch (Exception e)
        {
            logger.error("parse time fail! the time is " + date, e);
        }
        
        return false;
    }
    
    /**
     * 判断日期是否是周末
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isWeekend(String date)
    {
        try
        {
            Calendar cal = Calendar.getInstance();
            
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            
            cal.setTime(formatter.parse(date));
            int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (week == 6 || week == 0)
            {// 0代表周日,6代表周六
                return true;
            }
        }
        catch (ParseException e)
        {
            logger.error("parse time fail! the time is " + date, e);
        }
        
        return false;
    }
    
    
    /**
     * 获得年月
     * 
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return 秒
     */
    public static String getYearAndMonth(String date)
    {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat ymformatter = new SimpleDateFormat("yyyy-MM");
        try
        {
            Date sourceDate = formatter.parse(date);
            return ymformatter.format(sourceDate);
        }
        catch (ParseException e)
        {
            logger.error("parse date fail! the date is " + date, e);
        }
        return null;
    }
    
    /**
     * 获取简单的当前时间的日期字符串
     * 
     * @return
     */
    public static String getSimpDate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date());
    }
    
    /**
     * 获得当前时间
     * 
     * @return
     */
    public static String getCurDate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
    
    /**
     * 获得当前时间
     * 
     * @return
     */
    public static String getCurYearMonthDate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }
    
    /**
     * 把yyyy-MM-dd HH:mm:ss格式的字符串转换为日期对象
     * 
     * @return
     */
    public static Date convertNormalDate(String date)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            return sdf.parse(date);
        }
        catch (ParseException e)
        {
            logger.error("parse date to yyyy-MM-dd HH:mm:ss fail! the date is " + date);
        }
        return null;
    }
    
    /**
     * 获取yyyy-MM-dd HH:mm:ss格式的字符串的毫秒数
     * @param date
     * @return
     */
    public static Long getDateMillisecond(String date)
    {
        Date normalDate = convertNormalDate(date);
        
        if (null != normalDate)
        {
            return normalDate.getTime();
        }
        else
        {
            return null;
        }
    }
    
    /**
     * 判断日期是否是在N个月之内
     * @param yearMonth 需要判断的日期,格式为yyyyMM
     * @param month 几个月之内
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean contansYearMonth(String yearMonth, int month)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        try
        {
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(yearMonth));
            cal.add(Calendar.MONTH, month);
            
            if (cal.getTimeInMillis() < sdf.parse(sdf.format(new Date())).getTime())
            {
                return false;
            }
        }
        catch (ParseException e)
        {
            logger.error("parse yyyyMM fail! the yearMonth is " + yearMonth + "month:" + month, e);
        }
        return true;
    }

4、对两个list合并,并且去重
public static List<ContactPersonBeanSql> getNewContactPerson(List<ContactPersonBeanSql> dataBigList, List<ContactPersonBeanSql> mysqlList) {
        Map<String, ContactPersonBeanSql> map = new HashMap<>();
        for (ContactPersonBeanSql contactPersonBeanSql : dataBigList) {
            map.put(contactPersonBeanSql.getContact_phone(), contactPersonBeanSql);
        }
        for (ContactPersonBeanSql contactPersonBeanSql : mysqlList) {
            map.put(contactPersonBeanSql.getContact_phone(), contactPersonBeanSql);
        }
        ArrayList<ContactPersonBeanSql> contactPersonBeanSqls = new ArrayList<>();
        for (Map.Entry<String, ContactPersonBeanSql> entry : map.entrySet()) {
            contactPersonBeanSqls.add(entry.getValue());
        }
        return contactPersonBeanSqls;

    }
5、将json格式的文本读取并解析
String json = FileCopyUtils.copyToString(new FileReader(new File("D:/test.txt")));
List<Statics> list = new Gson().fromJson(json, new TypeToken<List<Statics>>() {
}.getType());
6、(持续更新中。。。。。。)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: