java对时间的处理(时间处理工具类)

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.union.test.XmlUtils;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.dom4j.DocumentException;
import org.json.JSONObject;
import org.omg.CORBA.PUBLIC_MEMBER;

/**
 * 时间工具类
 * 
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String MMDD = "MMdd";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static String getNowDatee(){return dateTimeNow(MMDD);}

    public static String getYyyyMmDd(){
        return dateTimeNow(YYYYMMDD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * string  转换 date
     **/
    public static Date string2Date(String time){
        SimpleDateFormat format =   new SimpleDateFormat( "yyyy-MM-dd" );
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static Date string2Dates(String time){
        SimpleDateFormat format =   new SimpleDateFormat( "yyyy-MM-dd hh:mm" );
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static Date string2Datess(String time){
        SimpleDateFormat format =   new SimpleDateFormat( "yyyy-MM-dd" );
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }
    
    /**
     * 获取yyyy-MM-dd HH:mm:ss格式日期字符串
     * @return
     */
    public static String getStringDate(){
    	SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(s.format(new Date()));
        return s.format(new Date());
    }
    
    /**
     * 获取yyyyMMdd格式日期字符串
     * @return
     */
    public static String getYyyyMMddDate(){
    	SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
        System.out.println(s.format(new Date()));
        return s.format(new Date());
    }

    /**
     * 根据值 获取 该时间
     * @param strs
     * @return
     */
    public static String getStrYear(String strs){
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        String str = "-"+strs;
        Date date = new Date();//获取当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, Integer.parseInt(str));//当前时间减去一年,即一年前的时间  
        return s.format(calendar.getTime());
    }

    /**
     * 获取上一天 时间 格式 yyyyMMdd
     * @return
     * @throws ParseException
     */
    public static final String getYesterday() throws ParseException {
        DateFormat d = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(d.parse(DateUtils.getDate()));
        c.set(Calendar.DATE, c.get(Calendar.DATE)-1);
        String t = d.format(c.getTime());
        String parseDate=t.replaceAll("-","");
        return parseDate;
    }

    /**
     * 获取上一天
     * @param dateTime
     * @return
     * @throws ParseException
     */
    public static final String getYesterDay(String dateTime) throws ParseException {
        DateFormat d = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(d.parse(dateTime));
        c.set(Calendar.DATE, c.get(Calendar.DATE)-1);
        String t = d.format(c.getTime());
        return t;
    }

    /**
     * 获取上个月最后一天
     * @param dateTime
     * @return
     */
    public static final String getYueLastDay(String dateTime){
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar=Calendar.getInstance();
        try {
            calendar.setTime(sf.parse(dateTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int month=calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month-1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String date=sf.format(calendar.getTime());
        return date;
    }

    /**
     * 取得上上季度最后一天日期
     * @param date 日期
     * @return
     */
    public static String getLastDay(String date) throws ParseException {
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
        //取得日历
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sf.parse(date));

        // 日历减6个月,即上上季度
        calendar.add(Calendar.MONTH,-3);

        int year = calendar.get(Calendar.YEAR);// 上上季度的年份
        int mouth = calendar.get(Calendar.MONTH);// 上上季度的月份
        String mmdd = "";// 月/日
        // 根据月份,判断是哪个季度
        switch( mouth){
            case 1:
            case 2:
            case 3:
                mmdd = "3-31"; // 第一季度最后一天是3/31
                break;
            case 4:
            case 5:
            case 6:
                mmdd = "6-30"; // 第二季度最后一天是6/30
                break;
            case 7:
            case 8:
            case 9:
                mmdd = "9-30";// 第三季度最后一天是9/30
                break;
            case 10:
            case 11:
            case 12:
                mmdd = "12-31";// 第四季度最后一天是12/31
                break;
        }

        String lastDate = String.valueOf(year) + "-" + mmdd;
        return lastDate;
    }

    /**
     * 获取上一年
     * @param dateTime
     * @return
     * @throws ParseException
     */
    public static int getShangNian(String dateTime) throws ParseException {
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar curr = Calendar.getInstance();
        curr.setTime(sf.parse(dateTime));
        curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)-1);
        int date=curr.get(Calendar.YEAR);
        return date;
    }

    /**
     * 获取某年最后一天日期
     * @return Date
     */
    public static String getYearLast(String dateTime) throws ParseException {
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar curr = Calendar.getInstance();
        curr.setTime(sf.parse(dateTime));
        curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)-1);
        int date=curr.get(Calendar.YEAR);
        curr.clear();
        curr.set(Calendar.YEAR, date);
        curr.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = curr.getTime();
        return sf.format(currYearLast).toString();
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 判断时间是否在时间段内
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 两个时间段 相差多少天
     * @param date 开始时间
     * @return
     */
    public static String getDay(String date){
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //String date="2019-06-05 12:00:01";
        Date startDate= null;
        try {
            startDate = dateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date beginDate=new Date();//当前时间
        long nd = 1000 * 24 * 60 * 60;
        // 获得两个时间的毫秒时间差异
        long diff = beginDate.getTime() - startDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        return String.valueOf(day);
    }

    /**
     * .Description://根据字符日期返回星期几
     * .Author:麦克劳林
     * .@Date: 2018/12/29
     */
    public static String getWeek(String dateTime){
        String week = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(dateTime);
            SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
            week = dateFm.format(date);
            week=week.replaceAll("星期","周");
        }catch (ParseException e){
            e.printStackTrace();
        }
        return week;
    }

    /**
     * 获取过去7天内的日期数组
     * @param intervals      intervals天内
     * @return              日期数组
     */
    public static ArrayList<String> getDays(int intervals) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = intervals -1; i >= 0; i--) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }
    /**
     * 获取过去第几天的日期
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    public static String getFirstDayOfMonth(int month) {
        Calendar cal = Calendar.getInstance();
        // 设置月份
        cal.set(Calendar.MONTH, month - 1);
        // 获取某月最小天数
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        // 设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = sdf.format(cal.getTime())+" 00:00:00";
        return firstDayOfMonth;
    }

    /**
     * 获得该月最后一天
     *
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int month) {
        Calendar cal = Calendar.getInstance();
        // 设置月份
        cal.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        int lastDay=0;
        //2月的平年瑞年天数
        if(month==2) {
            lastDay = cal.getLeastMaximum(Calendar.DAY_OF_MONTH);
        }else {
            lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        // 设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }

    public static List<String> getSixMonth(String date) {
        //返回值
        List<String> list = new ArrayList<String>();
        int month = Integer.parseInt(date.substring(6, 7));
        int year = Integer.parseInt(date.substring(0, 4));
        for (int i = 6; i >= 0; i--) {
            if (month > 7) {
                if (month - i >= 10) {
                    list.add(year + "-" + String.valueOf(month - i));
                } else {
                    list.add(year + "-0" + String.valueOf(month - i));
                }
            } else {
                if (month - i <= 0) {
                    if (month - i + 12 >= 10) {
                        list.add(String.valueOf(year - 1) + "-" + String.valueOf(month - i + 12));
                    } else {
                        list.add(String.valueOf(year - 1) + "-0" + String.valueOf(month - i + 12));
                    }
                } else {
                    if (month - i >= 10) {
                        list.add(String.valueOf(year) + "-" + String.valueOf(month - i));
                    } else {
                        list.add(String.valueOf(year) + "-0" + String.valueOf(month - i));
                    }
                }
            }
        }
        return list;

    }

    /**
     *  往前数 6个月 每个月末的日期
     * @param date 2020-04
     * @return
     */
    public static List<String> getSixM(String date){
        List<String> list = getSixMonth(date);
        list.remove(6);
        List<String> dateList = new ArrayList<>();
        for(String str:list){
            String [] arr = str.split("-");
            String dates = str+DateUtils.getLastDayOfMonth(Integer.parseInt(arr[1]));
            dateList.add(dates.replace("-",""));
        }
        return dateList;
    }

    /**
     * 获取当前年月
     * @return 2020-04
     */
    public static String getNowYue(){
        String aa = "";
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH )+1;
        if(month < 10){
            aa = year + "-0" + month;
        }else {
            aa = year + "-" + month;
        }
         return aa;
    }

    /**
     * 获取指定日期的前一天
     * @param today
     * @return
     */
    public static Integer getQianDay(Integer today){
        SimpleDateFormat sj = new SimpleDateFormat("yyyyMMdd");
        Date d = null;
        try {
            d = sj.parse(today.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.DATE, 1);
        calendar.add(calendar.DATE, -2);
        Integer dates = Integer.parseInt(sj.format(calendar.getTime()));
        return dates;
    }

    /**
     * 元转换为万单位
     * @param number
     * @return
     */
    public static String toNumber1(Double number) {
        String str = "";
        if (number <= 0) {
            str = "";
        } else {
            double d = (double) number;
            //将数字转换成万
            double num = d / 10000;
            BigDecimal b = new BigDecimal(num);
            //四舍五入保留小数点后一位
            double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            str = f1+"";
        }
        return str;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值