java时间日期工具类

 转载请标明出处:
java时间日期工具类_付付讶的博客-CSDN博客

本文出自付付讶的博客   

package com.wyzz.model.common.utils;


import com.wyzz.model.constant.PayConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDateTime;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.time.Instant;

/**
 * 时间工具类
 *
 * @author fuling
 * @date 2021/12/6 19:29
 */
public class DateUtils {
    public static final String DEFAULT_FORMAT_DATETIME="yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_FORMAT_Hour="yyyy-MM-dd HH";
    public static final String DEFAULT_FORMAT_DATE="yyyy-MM-dd";
    public static final String DEFAULT_FORMAT_TIME="HH:mm:ss";
	
    private static final List<String> FORMATLIST = new ArrayList(4);

    static {
        FORMATLIST.add("yyyy-MM");
        FORMATLIST.add("yyyy-MM-dd");
        FORMATLIST.add("yyyy-MM-dd hh:mm");
        FORMATLIST.add("yyyy-MM-dd hh:mm:ss");
    }
	
	 /**
     * 一秒中包含毫秒数的常数
     */
    static final long ONE_SECOND = 1000L;
    /**
     * 一分钟包含秒数的常数
     */
    static final long MINUTES_CONSTANT = 60L;
	
	//日期格式
    private static SimpleDateFormat year_format = new SimpleDateFormat("yyyy");

    public static SimpleDateFormat default_format = new SimpleDateFormat(
            "yyyy-MM-dd");

    public static SimpleDateFormat common_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static SimpleDateFormat time_format = new SimpleDateFormat(
            "yyyyMMddHHmmss");

    public static SimpleDateFormat times_format = new SimpleDateFormat(
            "yyyyMMddHHmmssSSS");

    protected static Log log = LogFactory.getLog(DateUtils.class);
	
	
	
	 /**
     * 日期字符串转date
     *
     * @param dateStr 日期字符串
     * @param format  转换格式
     * @return
     */
    public static Date formatDate(String dateStr, String format) {
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            date = sdf.parse(dateStr);
        } catch (Exception e) {

        }
        return date;

    }

    /**
     * date转字符串
     *
     * @param date   日期
     * @param format 转换格式
     * @return
     */
    public static String parseDate(Date date, String format) {
        String dateStr = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            dateStr = sdf.format(date);
        } catch (Exception e) {
            throw new RuntimeException("cant not format Date to String for date:"+date);
        }
        return dateStr;

    }
	
	/**
     * 得到当前时间,返回long型
     *
     * @return String
     */
    public static long generateLongTime() {
        Date dt = new Date();
        return dt.getTime();
    }

    /**
     * 得到当前时间,格式为yyyy-MM-dd HH:mm:ss
     *
     * @return String
     */
    public static String nowTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }

    /**
     * 得到当前时间,格式为yyyy-MM
     *
     * @return String
     */
    public static String nowTimeMonth() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        return format.format(new Date());
    }

    /**
     * 得到当前时间,格式为yyyyMMddHHmmss
     *
     * @return String
     */
    public static String generateTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(new Date());
    }

    /**
     * 得到当前时间,yyyyMMddHHmmssSSS
     *
     * @return String
     */
    public static String generateTimes() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return format.format(new Date());
    }
	
	/**
     * 得到当前日期,yyyy-MM-dd
     *
     * @return
     */
    public static String getCurrentDate() {
        Calendar c = Calendar.getInstance();
        Date date = c.getTime();
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        return simple.format(date);
    }

    /**
     * 得到昨天日期,yyyy-MM-dd
     *
     * @return
     */
    public static String getYesterdayDate(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(calendar.DATE,-1);
        String date2= sdf.format(calendar.getTime());
        System.out.println(date2);
        return date2;
    }
	
	 /**
     * 获取当前时间前一天
     * @return 时间结果
     */
    public static Date getCurDate() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_YEAR, -1);
        return instance.getTime();
    }
	
	 /**
     * 返回本年份_格式yyyy
     *
     * @return int
     */
    public static int getCurrYear() {
        return new GregorianCalendar().get(Calendar.YEAR);
    }
	
	/**
     * 返回下一年_格式yyyy
     *
     * @return int
     */
    public static int getNextYear() {
        return new GregorianCalendar().get(Calendar.YEAR) + 1;
    }

    /**
     * 根据格式生成当前日期时间
     *
     * @param formatStr
     * @return
     */
    public static String generateDateTime(String formatStr) {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        return format.format(new Date());
    }

     /**
     * 根据格式生成当前日期时间+小时
     * @param formatStr
     * @return
     */
    public static String generateDateTimeAddHour(int addHour,String formatstr){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR_OF_DAY, addHour);
        SimpleDateFormat format = new SimpleDateFormat(formatstr);
        return format.format(cal.getTime());
    }
    /**
     * 根据格式生成指定日期时间
     * @param date
     * @param formatStr
     * @return
     */
    public static String generateDateTime(Date date,String formatStr){
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        return format.format(date);
    }

    /**
     * 根据生日计算年龄
     * @param birthday 生日字符串
     * @param formatter 日期格式
     * @return 年龄
     */
    public static int getAgeByBirthday(String birthday,String formatter){
        return getAgeByBirthday(formatDate(birthday, formatter));
    }

    /**
     * 出生日期距今未满一周年,记0周岁;当前日期和出生日期同一天,生日没过完则年龄需-1;当前日期大于出生日期
     *
     * 根据生日计算年龄
     * @param birthday 生日
     * @return
     */
    public static int getAgeByBirthday(Date birthday){
        int age=0;
        Calendar now=Calendar.getInstance();
        now.setTime(new Date());
        Calendar birth=Calendar.getInstance();
        birth.setTime(birthday);

        //如果生日比当前日期晚,就是0岁
        if(birth.after(now)){
            age=0;
        }else{
            age=now.get(Calendar.YEAR)-birth.get(Calendar.YEAR);//计算年份差,例如:2019-2018=1
            if(age!=0 && now.get(Calendar.DAY_OF_YEAR)<=birth.get(Calendar.DAY_OF_YEAR)){
                //如果当前日期早于出生日期,则年龄-1
                age-=1;
            }
        }
        return age;
    }
	
	/**
     * 根据指定季度返回季度包含月份
     * @param quarter 季度
     * @return 当前季度所包含的月份
     */
    public static List<String> getMonthsByQuarter(int quarter){
        List<String> months=new ArrayList<>();
        String year=String.valueOf(getCurrYear());
        switch(quarter){
            case 1:
                months.add(year+"-01");
                months.add(year+"-02");
                months.add(year+"-03");
                break;
            case 2:
                months.add(year+"-04");
                months.add(year+"-05");
                months.add(year+"-06");
                break;
            case 3:
                months.add(year+"-07");
                months.add(year+"-08");
                months.add(year+"-09");
                break;
            case 4:
                months.add(year+"-10");
                months.add(year+"-11");
                months.add(year+"-12");
                break;
        }
        return months;
    }
	
	 /**
     * 根据指定年份与季度返回季度包含月份
     * @param year 年份
     * @param quarter 季度
     * @return 当前季度所包含的月份
     */
    public static List<String> getMonthsByQuarter(String year,int quarter){
        List<String> months=new ArrayList<>();
        if(StringUtils.isEmpty(year)){
            return getMonthsByQuarter(quarter);
        }
        switch(quarter){
            case 1:
                months.add(year+"-01");
                months.add(year+"-02");
                months.add(year+"-03");
                break;
            case 2:
                months.add(year+"-04");
                months.add(year+"-05");
                months.add(year+"-06");
                break;
            case 3:
                months.add(year+"-07");
                months.add(year+"-08");
                months.add(year+"-09");
                break;
            case 4:
                months.add(year+"-10");
                months.add(year+"-11");
                months.add(year+"-12");
                break;
        }
        return months;
    }

    /**
     * 根据月份返回当前季度
     * @param month 月份
     * @return 当前月份所处季度
     */
    public static int parseQuarter(int month) {
        int quarter = 0;
        switch (month) {
            case 1:
            case 2:
            case 3:
                quarter = 1;
                break;
            case 4:
            case 5:
            case 6:
                quarter = 2;
                break;
            case 7:
            case 8:
            case 9:
                quarter = 3;
                break;
            case 10:
            case 11:
            case 12:
                quarter = 4;
                break;
            default:
                break;
        }
        return quarter;
    }
	
	/**
     * 根据yyyy-MM-dd得到月份
     *
     * @param dateString
     *            String
     * @return int
     */
    public static int getMonthFromYear(String dateString) {
        Date date = string2Date(dateString);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 得到指定月份的所有天数
     * @param month 月份
     * @return 当前月份所处季度
     */
    public static int getDaysOfMonth(String date,String format){
        Calendar ca=Calendar.getInstance();
        ca.setTime(formatDate(date,format));
        return ca.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 得到指定年的所有天数
     *
     * @param year
     *            String
     * @return day int
     */
    public static int getDayFromYear(String year) {
        Date date;
        int day = 0;
        try {
            date = year_format.parse(year);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            day = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
        } catch (ParseException e) {

        }
        return day;
    }

    /**
     * 获取某年第一天日期_格式yyyy-MM-dd
     *
     * @param year
     *            年份
     * @return String
     */
    public static String getCurrYearFirstDay(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return default_format.format(currYearFirst);
    }

    /**
     * 根据一个日期,返回是星期几的数字_星期一:1....星期六:6,星期天:7,
     * 注意:日期输错,不会报错,例如:2月30或31号
     *
     * @param date
     *            日期值
     * @return int
     */
    public static int getWeek(Date date) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int iDay = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            iDay = 7;
        } else {
            iDay = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return iDay;
    }

    /**
     * 根据一个日期,返回是星期几的数字_星期一:1....星期六:6,星期天:7,
     * 注意:日期输错,不会报错,例如:2月30或31号
     *
     * @param dateString
     *            String
     * @return int
     */
    public static int getWeek(String dateString) {
        Date date = string2Date(dateString);
        Calendar c = Calendar.getInstance();
        c.setTime(date);

        int iDay = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            iDay = 7;
        } else {
            iDay = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return iDay;
    }

    /**
     * 根据一个日期,传入指定天数,想要返回长度,得到String
     *
     * @param inDate
     *            日期
     * @param days
     *            天数
     * @param _iType
     *            inDate长度
     * @return String
     */
    public static String getDateByAddDays(String inDate, int days, int _iType) {
        Date dateStr = string2Date(inDate);
        Date tempDate = getDateByAddDays(dateStr, days);
        return date2String(tempDate, _iType);
    }

    /**
     * 根据Date日期,传入返回长度,得到String
     *
     * @param date
     *            Date
     * @param _iType
     *            返回String长度
     * @return String
     */
    public static String date2String(Date date, int _iType) {
        String strTemp = time_format.format(date);
        SimpleDateFormat formatter = null;
        switch (_iType) {
            case 0: // yyyymmdd
                strTemp = strTemp.substring(0, 8);
                break;
            case 4:// yyyy
                strTemp = strTemp.substring(0, 4);
                break;
            case 6: // yymmdd
                strTemp = strTemp.substring(2, 8);
                break;
            case 8: // yyyymmdd
                strTemp = strTemp.substring(0, 8);
                break;
            case 14:
                // yyyyMMddHHmmss 格式
                break;
            case 10: // yyyy-mm-dd
                formatter = new SimpleDateFormat("yyyy-MM-dd");
                strTemp = formatter.format(date);
                break;
            case 19: // yyyy-mm-dd HH:mm:ss
                formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                strTemp = formatter.format(date);
                break;
            case -6: // HHmmss
                strTemp = strTemp.substring(8);
                break;
            case -8: // HH:mm:ss
                formatter = new SimpleDateFormat("HH:mm:ss");
                strTemp = formatter.format(date);
                break;
            default:
                break;
        }
        return strTemp;
    }
	
	/**
     * 根据Date日期,传入返回长度,得到String
     *
     * @param  long
     *
     * @param _iType
     *            返回String长度
     * @return String
     */
    public static String longDate2String(long lDate, int _iType) {

        Date date = new Date(lDate);
        String strTemp = time_format.format(date);
        SimpleDateFormat formatter = null;
        switch (_iType) {
            case 0: // yyyymmdd
                strTemp = strTemp.substring(0, 8);
                break;
            case 4:// yyyy
                strTemp = strTemp.substring(0, 4);
                break;
            case 6: // yymmdd
                strTemp = strTemp.substring(2, 8);
                break;
            case 8: // yyyymmdd
                strTemp = strTemp.substring(0, 8);
                break;
            case 10: // yyyy-mm-dd
                formatter = new SimpleDateFormat("yyyy-MM-dd");
                strTemp = formatter.format(date);
                break;
            case -6: // HHmmss
                strTemp = strTemp.substring(8);
                break;
            case -8: // HH:mm:ss
                formatter = new SimpleDateFormat("HH:mm:ss");
                strTemp = formatter.format(date);
                break;
            default:
                break;
        }
        return strTemp;
    }

    /**
     * 获得指定日期前后的日期,返回日期型值
     *
     * @param inDate
     *            指定的日期
     * @param days
     *            加减天数
     * @return Date
     *
     */
    public static Date getDateByAddDays(Date inDate, int days) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(inDate);
        calendar.add(Calendar.DATE, days);
        return calendar.getTime();
    }
	
	/**
     * 获得指定日期前后的日期,返回字符串型值
     *
     * @param inDate
     *            指定的日期
     * @param days
     *            加减天数
     * @return String
     *
     */
    public static String getDateByAddDays(String formatStr, int days) {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, days);
        return format.format(calendar.getTime());
    }

    /**
     * 获得指定分钟前后的时间,返回日期型值
     *
     * @param inDate
     *            指定的日期
     * @param minutes
     *            加减分钟
     * @return Date
     *
     */
    public static Date getDateByAddMinutes(Date inDate, int minutes) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(inDate);
        calendar.add(Calendar.MINUTE, minutes);
        return calendar.getTime();
    }


    /**
     * 获得指定日期前后的日期,返回日期格式
     *
     * @param inDate
     *            指定日期
     * @param month
     *            加减月数
     * @return
     */
    public static Date getDateByAddMonth(Date inDate, int month) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(inDate);
        calendar.add(Calendar.MONTH, month);
        return calendar.getTime();
    }

    /**
     * 当前日期的前后日期,返回字符串格式 yyyyMMddHHmmss
     *
     * @param month
     *            加减月数
     * @return
     */
    public static String getCurrentByAddMonth(int month) {
        Date d = getDateByAddMonth(new Date(), month);

        return date2String(d, 14);
    }

    /**
     * 得到两个时间的差值,单位是小时
     *
     * @param beginDate
     * @param endDate
     * @return double
     */
    public static double getHourBetweenDates(Date beginDate, Date endDate) {

        long l1 = endDate.getTime();
        long l2 = beginDate.getTime();

        double cc = l1 - l2;
        return cc / (60 * 60 * 1000);
    }

    /**
     * 得到两个时间的差值,单位是分钟
     *
     * @param beginDate
     * @param endDate
     * @return double
     */
    public static double getMinuteBetweenDates(Date beginDate, Date endDate) {

        double cc = endDate.getTime() - beginDate.getTime();
        return cc / (60 * 1000);
    }
	
	/**
     * 得到两个时间的差值,单位是秒
     * @param date1
     * @param date2
     * @return long
     */
    public static Long getDateBetween(Date date1, Date date2) {

        return Math.abs((date1.getTime() - date2.getTime()) / 1000);
    }
	
	/**
     * 得到两个时间的差值,单位是天数
     * @param date1
     * @param date2
     * @return int
     */
    public static int differentDays(Date date1,Date date2){
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        //不同一年
        if(year1 != year2){
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++){
                //闰年
                if(i%4==0 && i%100!=0 || i%400==0){
                    timeDistance += 366;
                    //不是闰年
                } else{
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2-day1) ;
            //同一年
        }else {
            return day2-day1;
        }
    }

    /**
     * 获得月份英文缩写
     *
     * @param sMonth
     *            String
     * @return String
     */
    public static String getMonthEnglishName(String sMonth) {

        String[] arrMonth = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};

        int iMonth = 0;
        String sRet = "";
        try {
            iMonth = Integer.parseInt(sMonth);
            if (iMonth >= 1 && iMonth <= 12) {
                sRet = arrMonth[iMonth -1];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sRet;
    }

    /**
     * @param date1
     *            需要比较的时间 不能为空(null),需要正确的日期格式
     * @param date2
     *            被比较的时间 为空(null)则为当前时间
     * @param stype
     *            返回值类型 0为多少天,1为多少个月,2为多少年
     * @return
     */
    @SuppressWarnings("unused")
    public static int compareDate(String date1, String date2, int stype) {
        int n = 0;

        String[] u = { "天", "月", "年" };
        String formatStyle = stype == 1 ? "yyyy-MM" : "yyyy-MM-dd";

        date2 = date2 == null ? DateUtils.getCurrentDate() : date2;

        DateFormat df = new SimpleDateFormat(formatStyle);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(df.parse(date1));
            c2.setTime(df.parse(date2));
        } catch (Exception e3) {
            e3.printStackTrace();
        }
        // List list = new ArrayList();
        while (!c1.after(c2)) { // 循环对比,直到相等,n 就是所要的结果
            // list.add(df.format(c1.getTime())); // 这里可以把间隔的日期存到数组中 打印出来
            n++;
            if (stype == 1) {
                c1.add(Calendar.MONTH, 1); // 比较月份,月份+1
            } else {
                c1.add(Calendar.DATE, 1); // 比较天数,日期+1
            }
        }

        n = n - 1;

        if (stype == 2) {
            n = (int) n / 365;
        }

        return n;
    }

    

    /**
     * 根据日期判断出星期几
     * @param date
     * @return
     */
    public static String  CalculateWeekDay(String date) {
        String[] str = date.split("-");
        int y = Integer.parseInt(str[0]);
        int m = 0;
        if(str[1].startsWith("0")){
            m = Integer.parseInt(str[1].substring(1));
        }else{
            m = Integer.parseInt(str[1]);
        }
        int d = Integer.parseInt(str[2]);
        if (m == 1 || m == 2) {
            m += 12;
            y--;
        }
        int iWeek = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
        switch (iWeek) {
            case 0:
                return "星期一";
            case 1:
                return "星期二";
            case 2:
                return "星期三";
            case 3:
                return "星期四";
            case 4:
                return "星期五";
            case 5:
                return "星期六";
            case 6:
                return "星期日";
        }
        return "";
    }


    /**
     * 获取当前周开始时间和结束时间(周一-周日)
     * @return 年月日
     */
    public static String[] getWeekRange(){
        LocalDate today = LocalDate.now();
        DayOfWeek week = today.getDayOfWeek();
        int dayValue = week.getValue();
        String weekStart = today.minusDays(dayValue - 1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String weekEnd = today.plusDays(7 - dayValue).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return new String[]{weekStart,weekEnd};
    }
	
	 /**
     * 获取当前周开始时间和结束时间(周一-周日)
     * @return 年月日时分秒
     */
    public static Date[] getWeekRangeDate()  {
        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        // 本周开始时间
        Date startTimeInWeek = now.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withDayOfWeek(DateTimeConstants.MONDAY).toDate();
        // 本周结束时间
        Date endTimeInWeek = now.withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withDayOfWeek(DateTimeConstants.SUNDAY).toDate();
        return new Date[]{startTimeInWeek,endTimeInWeek};
    }

    /**
     * 获取当前周开始时间和结束时间(周一-周五)
     * @return 起止时间
     */
    public static String[] getWorkRange(){
        LocalDate today = LocalDate.now();
        DayOfWeek week = today.getDayOfWeek();
        int dayValue = week.getValue();
        String weekStart = today.minusDays(dayValue - 1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String weekEnd = today.plusDays(5 - dayValue).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return new String[]{weekStart,weekEnd};
    }

   
    /**
     * 获取指定月开始时间和结束时间
     * @param month 月份:yyyy-MM-dd
     * @return 起止时间
     */
    public static String[] getMonthRange(String month){
        //获取本月第一天和最后一天日期
        DateTimeFormatter format=DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate firstDay = LocalDate.parse(month,format).with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDay = LocalDate.parse(month,format).with(TemporalAdjusters.lastDayOfMonth());
        return new String[]{firstDay.format(format),lastDay.format(format)};
    }
    /**
     * 获取当季度开始时间和结束时间
     * @return 起止时间
     */
    public static String[] getQuarterRange(){
        List<String> months=getMonthsByQuarter(parseQuarter(Integer.valueOf(generateDateTime("MM"))));
        //获取本月第一天和最后一天日期
        DateTimeFormatter format=DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String lastDay = getMonthRange(months.get(2)+"-01")[1];
        return new String[]{months.get(0)+"-01",lastDay};
    }

    /**
     * 获取某个日期的开始时间
     * @return 起止时间
     */
    public static Date getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if(null != d) {calendar.setTime(d);}
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),    calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    /**
     * 获取某个日期的结束时间
     * @return 起止时间
     */
    public static Date getDayEndTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if(null != d) {calendar.setTime(d);}
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),    calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取当月开始时间和结束时间
     * @return date
     */
    public static Date[] getMonthRangeDate()  {
        LocalDate today = LocalDate.now();
        //本月的第一天
        LocalDate firstDay = LocalDate.of(today.getYear(), today.getMonth(), 1);
        Date startTimeInMonth = Date.from(firstDay.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
        //本月的最后一天
        LocalDate lastDay = today.with(TemporalAdjusters.lastDayOfMonth());
        Date endTimeInMonth = Date.from(lastDay.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
        return new Date[]{getDayStartTime(startTimeInMonth),getDayEndTime(endTimeInMonth)};
    }
	
	 /**
     * 获取当月开始时间和结束时间
     * @return String
     */
    public static String[] getMonthRange(){
        //获取本月第一天和最后一天日期
        return getMonthRange(generateDateTime("yyyy-MM-dd"));
    }
	
    /**
     * 获取上月开始时间和结束时间
     * @return 起止时间
     */
    public static Date[] getBeforeMonthRangeDate()  {
        LocalDate today = LocalDate.now().plusMonths(-1);
        //本月的第一天
        LocalDate firstDay = LocalDate.of(today.getYear(), today.getMonth(), 1);
        Date startTimeInMonth = Date.from(firstDay.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
        //本月的最后一天
        LocalDate lastDay = today.with(TemporalAdjusters.lastDayOfMonth());
        Date endTimeInMonth = Date.from(lastDay.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
        return new Date[]{getDayStartTime(startTimeInMonth),getDayEndTime(endTimeInMonth)};
    }

    /**
     * 获取距离今天结束还有多少秒
     * @return 秒数
     */
    public static long getSecondByEndToday() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR,1);
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.MILLISECOND,0);
        return ((calendar.getTimeInMillis()-System.currentTimeMillis()) / 1000) ;
    }

    /**
     * 获取距离本月结束还有多少秒
     * @return 秒数
     */
    public static long getSecondByMonthEndDay() {
        Date date = getMonthRangeDate()[1];
        return ((date.getTime()-System.currentTimeMillis()) / 1000) ;
    }
	
	
	
	/**
     * 将毫秒转换为秒
     *
     * @param timeInMillis
     * @return 秒值
     */
    public static int toSecs(long timeInMillis) {
        return (int) Math.ceil((double) timeInMillis / ONE_SECOND);
    }

    /**
     * 将毫秒转换为分钟
     *
     * @param timeInMillis
     * @return 分钟
     */
    public static int toMinutes(long timeInMillis) {
        return (int) Math.ceil((double) timeInMillis / ONE_SECOND / MINUTES_CONSTANT);
    }

    /**
     * 将秒转换为毫秒,精度为1秒
     *
     * @param timeInSecs 秒值
     * @return 毫秒值
     */
    public static long toMillis(int timeInSecs) {
        return timeInSecs * ONE_SECOND;
    }

    /**
     * 将长秒值转换为int秒值并考虑溢出
     * 通过切换到整数. max_value从向下转换。
     *
     * @param seconds 毫秒值
     * @return 相同的整型值,除非长整数>。MAX_VALUE在这种情况下返回MAX_VALUE
     */
    public static int convertTimeToInt(long seconds) {
        if (seconds > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        } else {
            return (int) seconds;
        }
    }

    /**
     * 获取当前的秒值
     *
     * @return 当前日期秒值
     */
    public static int currentSecond() {
        return toSecs(System.currentTimeMillis());
    }

    /**
     * 获取当前毫秒值
     *
     * @param isDay 是否携带时分秒 true 是 false 否
     * @return 毫秒值
     */
    public static int currentSecond(boolean isDay) {
        if (isDay) {
            return currentSecond();
        }
        Date current = new Date();
        current = new Date(current.getYear(), current.getMonth(), current.getDate());
        return toSecs(current.getTime());
    }
	
	/**
     * 根据毫秒值判断日期是否是今天
     *
     * @param second 毫秒值
     * @return 是否是今天
     */
    public static boolean isToday(Integer second) {
        //获取当前日期
        LocalDate now = LocalDate.now();
        //获取传入毫秒日期
        Instant instant = Instant.ofEpochSecond(second);
        LocalDate localDate = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();
        return now.equals(localDate);
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值