美文网首页
日期工具类

日期工具类

作者: Mark_ZSQ | 来源:发表于2019-10-29 17:57 被阅读0次
package com.ltkj.pmc.utility;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
 * Date 工具类
 * @author zhangshiqiang
 */
public class TimeUtils {

    private static SimpleDateFormat sdf;
    private static SimpleDateFormat strSdf;
    private static SimpleDateFormat getSdf(int type) {
        if(type == 1){
            return sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }else if(type == 2 || type == 0){
            return sdf = new SimpleDateFormat("yyyy-MM-dd");
        }else if(type == 3){
            return sdf = new SimpleDateFormat("yyyy-M-d HH:mm:ss");
        }else if(type == 4){
            return sdf = new SimpleDateFormat("yyyyMMdd");
        }else if(type == 5){
            return sdf = new SimpleDateFormat("yyyy-M-d");
        }else{
            return sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        }
    }

    /**
     * 获取当前时间
     * @return
     */
    public static Date getCurrentDateYMDHMSFORDATE(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try{
            date = new Date();
        }catch (Exception e){

        }
        return date;
    }

    public static String getCurDate(int type){
        String date = null;
        sdf = getSdf(type);
        try{
            date = sdf.format(new Date());
        }catch (Exception e){

        }
        return date;
    }

    /**
     * 获取当前时间
     * @return
     */
    public static Date getCurrentDateYMDHMS(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try{
            date = new Date();
        }catch (Exception e){

        }
        return date;
    }

    /**
     * 获取当前时间 格式:YYYY-MM-dd
     * @return
     */
    public static java.time.LocalDate getLocalDateYMDHMS(){
        DateTimeFormatter sdf =  DateTimeFormatter.ofPattern("YYYY-MM-dd");
        LocalDate date = LocalDate.now();
        return date;
    }

    /**
     * 获取当前时间 格式:YYYY-MM-dd HH:mm:ss
     * @return
     */
    public static java.time.LocalDateTime getLocalDateTimeYMDHMS(){
        DateTimeFormatter sdf =  DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
        LocalDateTime date = LocalDateTime.now();
        return date;
    }

    /**
     *      昨天
     * */
    public static String getYesterdayDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nextDay = getDateWithInterval(-1);
        return nextDay;
    }

    /**
     *     明天
     * */
    public static String getTomorrowDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nextDay = getDateWithInterval(+1);
        return nextDay;
    }

    /**
     *    根据时间加个获取时间
     * */
    public static String getDateWithInterval(int interval) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String returnDate = null;
        try{
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH, interval);
            date = calendar.getTime();
            returnDate = sdf.format(date);
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnDate;
    }


    /**
     *      给日期 +1 天 , 参数格式为 : 2018-01-31
     * */
    public static String addOneDay(String dateStr){
        try {
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
            Date date = f.parse(dateStr);
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(Calendar.DAY_OF_MONTH, 1);//  end date +1天
            dateStr = f.format(c.getTime());
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return dateStr;
    }

    /**
     * 根据时间 String 返回  Date
     * @param type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss  4为yyyyMMdd 5为 yyyy-M-d
     * @return
     */
    public static Date str2Date(String dateStr,int type){
        Date date = null;
        try {
            sdf = getSdf(type);
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 根据时间 String 返回  String
     * @param type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss  4为yyyyMMdd 5为 yyyy-M-d
     * @return
     */
    public static String strToStr(String dateStr,int type){
        String date = null;
        try {
            strSdf = getSdf(2);
            Date str2 = strSdf.parse(dateStr);
            sdf = getSdf(type);
            date = sdf.format(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 根据时间 Date 返回  String
     * @param type  type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss 4为yyyyMMdd 5为 yyyy-M-d
     * @return
     */
    public static String date2Str(Date date,int type){
        sdf = getSdf(type);
        return sdf.format(date);
    }


    //----------------- 首页  足迹  时间显示格式
    /**
     * 首页 足迹   显示的时间
     * @param date
     * @return  String[]  0 :月:1 1:日:1   2:时间:24:00
     */
    public static String[] formatDataByLogin(Date date){
        String[] reStr = new String[4];
        String dateStr = date2Str(date,3);
        String[] str1 = dateStr.split(" ");
        String fistStr = str1[0];
        String lastStr = str1[1];
        //年
        reStr[0] = (fistStr.split("-"))[0];
        //月
        reStr[1] = (fistStr.split("-"))[1];
        //日
        reStr[2] = (fistStr.split("-"))[2];
        //天
        reStr[3] = lastStr.substring(0,lastStr.lastIndexOf(":"));

        return reStr;
    }

    /**
     * 获得年
     * @return
     */
    public static String getYearByLogin(Date date){
        String[] str = formatDataByLogin(date);
        return str[0];
    }

    /**
     * 获得月
     * @return
     */
    public static String getMonthByLogin(Date date){
        String[] str = formatDataByLogin(date);
        int i = Integer.parseInt(str[1]);
        return marchConversionCapital(i)+"";
    }

    /**
     * 获得日
     * @return
     */
    public static String getDayByLogin(Date date){
        String[] str = formatDataByLogin(date);
        return str[2];
    }

    /**
     * 获得时间
     * @return
     */
    public static String getTimeByLogin(Date date){
        String[] str = formatDataByLogin(date);
        return str[3];
    }


    /**
     * 月份格式化后显示大写月份(一,三,九)
     * @param march
     * @return
     */
    public static String marchConversionCapital(int march){
        String marchCapital=new String();
        switch(march) {
            case 1:
                marchCapital="一";
                break;
            case 2:
                marchCapital="二";
                break;
            case 3:
                marchCapital="三";
                break;
            case 4:
                marchCapital="四";
                break;
            case 5:
                marchCapital="五";
                break;
            case 6:
                marchCapital="六";
                break;
            case 7:
                marchCapital="七";
                break;
            case 8:
                marchCapital="八";
                break;
            case 9:
                marchCapital="九";
                break;
            case 10:
                marchCapital="十";
                break;
            case 11:
                marchCapital="十一";
                break;
            case 12:
                marchCapital="十二";
                break;
            default:
                marchCapital="一";
                break;
        }
        return marchCapital;
    }
    /**
     * 计算日期相减
     * @param oldDate 以前的日期,格式为yyyy-MM-dd
     * @param newDate 现在的日期,格式为yyyy-MM-dd
     * @return
     */
    public static String dateSubtraction(String oldDate,String newDate){
        String[] a=newDate.split("-");
        String[] b=oldDate.split("-");
        int ya = Integer.valueOf(a[0]);
        int ma = Integer.valueOf(a[1]);
        int da = Integer.valueOf(a[2]);
        int yb = Integer.valueOf(b[0]);
        int mb = Integer.valueOf(b[1]);
        int db = Integer.valueOf(b[2]);
        int d,m,y;
        if(da-db>=0){
            d=da-db;
            if(ma-mb>=0){
                m=ma-mb;
                y=ya-yb;
            }else {
                ya=ya-1;
                m=ma-mb+12;
                y=ya-yb;
            }
        }else {
            ma=ma-1;
            d=da-db+30;
            if(ma-mb>=0){
                m=ma-mb;
                y=ya-yb;
            }else {
                ya=ya-1;
                m=ma-mb+12;
                y=ya-yb;
            }
        }
        String s=y+"岁"+m+"个月"+d+"天";
        return s;
    }

    /**
     * 根据   2010-02-05获得宝贝多大了       根据身份日期判断
     * @param birthday
     * @return
     */
    public static int getAge(String birthday) {
        String[] bStr = birthday.split("-");
        String curDate = date2Str(new Date(),2);
        String[] cStr = curDate.split("-");
        int ageY = Integer.parseInt(cStr[0]) - Integer.parseInt(bStr[0]);
        if((Integer.parseInt(bStr[1])-Integer.parseInt(cStr[1])) < 0){
            ageY-=1;
        }else if(Integer.parseInt(bStr[1]) == Integer.parseInt(cStr[1]) && (Integer.parseInt(bStr[2])-Integer.parseInt(cStr[2])) < 0 ){
            ageY-=1;
        }
        return ageY;
    }

    /**
     * 通过当前日期,获得该月的所有天数时间
     * @param date
     * @return
     */
    public static List<Date> getAllTheDateOftheMonth(Date date) {
        List<Date> list = new ArrayList<Date>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DATE, 1);

        int month = cal.get(Calendar.MONTH);
        while (cal.get(Calendar.MONTH) == month) {
            list.add(cal.getTime());
            cal.add(Calendar.DATE, 1);
        }
        return list;
    }
    /**
     * yyyy-MM-dd日期格式 加减日期
     * @param m 要被减的时间
     * @param m 被加减的天数
     * @param type  type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss 4为yyyyMMdd 5为 yyyy-M-d
     */
    public static String dayCount(Date date,int m,int type) {
        sdf = getSdf(type);
        Calendar cal=Calendar.getInstance();
        cal.setTime(date);
        //减1天
        cal.add(Calendar.DATE, m);
        return sdf.format(cal.getTime());
    }
    /**
     * yyyy-MM-dd日期格式 加减日期
     * @param m 要被减的时间
     * @param m 被加减的天数
     * @param type  type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss 4为yyyyMMdd 5为 yyyy-M-d
     */
    public static Date dayCountOfYear(Date date,int m,int type) {
        sdf = getSdf(type);
        Calendar cal=Calendar.getInstance();
        cal.setTime(date);
        //减1天
        cal.add(Calendar.YEAR, m);
        return cal.getTime();
    }


    /**
     *      处理分页
     * */

    public static List subInfosWithPageRows(String page,String rows, List infos){

        int from = (Integer.valueOf(page) - 1) * Integer.valueOf(rows);
        int toIndex =  Integer.valueOf(page) * Integer.valueOf(rows);
        from = from > infos.size() ? infos.size() : from;
        toIndex = toIndex > infos.size() ? infos.size() : toIndex;
        infos = infos.subList(from, toIndex);

        return infos;
    }

    /**
     * 获取当天零点时间
     * @return
     */
    public static Date getCurrentDateZero(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 验证字符串时间,是否在30天内
     * @param str
     * @return
     */
    public static boolean isValidDate(String str) {
        boolean convertSuccess=true;
        //时间格式定义
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前时间日期--nowDate
        String nowDate = format.format(new Date());
        //获取30天前的时间日期--minDate
        Calendar calc = Calendar.getInstance();
        calc.add(Calendar.DAY_OF_MONTH, -30);
        String minDate = format.format(calc.getTime());
        try {
            //设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            //获取字符串转换后的时间--strDate
            String strDate = format.format(format.parse(str));
            //判断传的STR时间,是否在当前时间之前,且在30天日期之后-----测试的时候打印输出结果
            if (nowDate.compareTo(strDate) >= 0 && strDate.compareTo(minDate) >= 0){
                convertSuccess = true;
            }else{
                convertSuccess = false;
            }
        } catch (ParseException e) {
            convertSuccess=false;
        }
        return convertSuccess;
    }
}

相关文章

网友评论

      本文标题:日期工具类

      本文链接:https://www.haomeiwen.com/subject/yuvgvctx.html