DateUtil常用的Api接口函数

DateUtil常用的Api接口函数

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Slf4j
public class DateUtils {
    public static final String YYYYMMDD = "yyyyMMdd";
    public static final String YYYYMMDD1 = "yyyy-MM-dd";//
    public static final String YYYYMMDDHHMMSS1 = "yyyy-MM-dd HH:mm:ss";

    /**
     * 按自定义日期格式格式化日期
     *
     * @param target
     * @param format
     * @return 格式化后的日期字符串,如果传入的日期对象为NULL,返回空字符串
     */

    public static String formatDate(String target, String format) {
        if (target == null) {
            return "";
        }
        return target;
    }

    /**
     * 当前时间字符串
     */
    public static String dateToString() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss").toString();
    }

    public static String todayString() {
        return formatDate(new Date(), YYYYMMDD);
    }

    public static String formatDate(Date target, String format) {
        if (target == null) {
            return "";
        }
        return new SimpleDateFormat(format).format(target);
    }

    public static Timestamp parseDate(String date, String format) throws ParseException {
        return new Timestamp(new SimpleDateFormat(format).parse(date).getTime());
    }

    public static String formatDate(String date, String fromFormat, String toFormat) throws ParseException {
        if (date == null || date.trim().length() == 0) {
            return null;
        }
        return formatDate(parseDate(date, fromFormat), toFormat);
    }

    public static String formateTimestame(String d) {
        if (d.contains(".")) {
            d = d.substring(0, d.lastIndexOf("."));
        }
        return d;
    }

    public static long calculateTimeDifference(String date1, String date2) throws ParseException {
        return parseDate(date2, YYYYMMDDHHMMSS1).getTime() - parseDate(date1, YYYYMMDDHHMMSS1).getTime();
    }

    public static long getCurrentTime() {
        return System.currentTimeMillis();
    }

    public static String formatTimeLongToStr(Long time, Long split) {
        return String.valueOf(time / split);
    }

    public static String formatHourDisplay(String hour) {
        try {
            Timestamp time = parseDate(hour, "yyyy-MM-dd HH");
            return formatDate(time, "yyyy-MM-dd HH:mm") + "-"
                    + formatDate(new Timestamp(time.getTime() + 3600000), "HH:mm");
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            return "";
        }
    }

    public static String getDate(String str) {
        return str.substring(0, 10);
    }

    /**
     * 将String 类型的秒数  转换为  HH:mm:ss  类型
     *
     * @param time
     * @return
     */
    public static String parseString2DateString(String time) {
        long ms = Integer.parseInt(time) * 1000;//毫秒数
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");//初始化Formatter的转换格式。
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        return formatter.format(ms);
    }

    /**
     * 时间转换成秒数
     *
     * @param time
     * @return
     */
    public static Integer parseString2TimeInteger(String time) {
        String[] split = time.split(":");
        Integer s = Integer.parseInt(split[0]) * 3600; //小时
        s += Integer.parseInt(split[1]) * 60; //分钟
        s += Integer.parseInt(split[2]); //秒
        return s;
    }

    /**
     * 两个时间相差秒数
     *
     * @param a 时间参数 1 格式:1990-01-01 12:00:00
     * @param b 时间参数 2 格式:2009-01-01 12:00:00
     * @return long
     */
    public static long getDistanceTimes(Date a, Date b) {
        long interval = (b.getTime() - a.getTime()) / 1000;
        return interval;
    }

    /**
     * 获取两个日期的间隔天数
     * @param a
     * @param b
     * @return
     */
    public static int getDistanceDay(Date a, Date b) {
        int interval = (int) (b.getTime() - a.getTime()) / (1000 * 60 * 60 *24);
        return interval;
    }

    /**
     * 获取本周第一天的日期
     *
     * @return
     */
    public static Date getCurrWeekFirst() {
        Calendar cal = Calendar.getInstance();
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        int day = cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        return cal.getTime();
    }

    /**
     * 获取本月第一天的日期
     *
     * @return
     */
    public static Date getCurrMonthFirst() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        return cal.getTime();
    }

    /**
     * 获取本季度第一天
     *
     * @return
     */
    public static Date getCurrQuarterFirst() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 4);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获取本年第一天
     *
     * @return
     */
    public static Date getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    private static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 报表日期格式化
     *
     * @param source
     * @param format
     * @return
     */
    public static String formatStatDate(String source, String format) {
        if (StringUtils.isNotBlank(source)) {
            source = source.trim();
            if (source.length() <= format.length())
                return source;
            return source.substring(0, format.length());
        }
        return "";
    }

    /**
     * 当天日期近1个月的日期列表
     * @return
     */
    public static List<String> getDates() {
        List<String> dates = new ArrayList<>();
        LocalDate now = LocalDate.now();
        LocalDate past = now.minus(30, ChronoUnit.DAYS);
        while (!now.isBefore(past)) {
            dates.add(past.toString());
            past = past.plusDays(1L);
        }
        return dates;
    }

    /**
     * 当天日期指定天数的日期列表
     * @return
     */
    public static List<String> getDates(long days) {
        List<String> dates = new ArrayList<>();
        LocalDate now = LocalDate.now();
        LocalDate past = now.minus(days, ChronoUnit.DAYS);
        while (!now.isBefore(past)) {
            dates.add(past.format(DateTimeFormatter.ofPattern("MM.dd")));
            past = past.plusDays(1L);
        }
        return dates;
    }
    /**
     * 获取指定日期的第一个时辰
     * @param date
     * @return
     */
    public static Date getStartDate(Date date){
        Calendar start = Calendar.getInstance();
        start.setTime(date);
        start.set(Calendar.HOUR, 0);
        start.set(Calendar.MINUTE, 0);
        start.set(Calendar.SECOND, 0);
        start.set(Calendar.MILLISECOND, 0);
        return start.getTime();
    }

    /**
     * 获取指定日期的最后一个时辰
     * @return
     */
    public static Date getEndTime(){
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

    /**
     * 返回判断当前时间是早、下、晚、凌晨的哪个时间段。
     * @return
     */
    public static int timePerods(Date time){
        long mT = 0l;
        long zT = 0l;
        long eT = 0l;
        long dT = 0l;
        long tm = 0l;
        try {
            mT = DateUtils.parseDate("06:00:00", "HH:mm:ss").getTime();
            zT = DateUtils.parseDate("12:00:00", "HH:mm:ss").getTime();
            eT = DateUtils.parseDate("18:00:00", "HH:mm:ss").getTime();
            dT = DateUtils.parseDate("24:00:00", "HH:mm:ss").getTime();
            tm = DateUtils.parseDate(DateUtils.formatDate(time,"HH:mm:ss"),"HH:mm:ss").getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (tm >= mT && tm < zT){  //早上
            return 0;
        }else if (tm >= zT && tm < eT){ //下午
            return 1;
        }else if (tm >= eT && tm < dT){  //晚上
            return 2;
        }else {  //凌晨
            return 3;
        }
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值