java8时间工具类

简介: `import java.sql.Timestamp;import java.text.DateFormat;import java.text.ParseException;import java.

`import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.
;

/**

  • Java8时间方法LocalDate和LocalDateTime

  • getYear() int 获取当前日期的年份

  • getMonth() Month 获取当前日期的月份对象

  • getMonthValue() int 获取当前日期是第几月

  • getDayOfWeek() DayOfWeek 表示该对象表示的日期是星期几

  • getDayOfMonth() int 表示该对象表示的日期是这个月第几天

  • getDayOfYear() int 表示该对象表示的日期是今年第几天

  • withYear(int year) LocalDate 修改当前对象的年份

  • withMonth(int month) LocalDate 修改当前对象的月份

  • withDayOfMonth(int dayOfMonth) LocalDate 修改当前对象在当月的日期

  • isLeapYear() boolean 是否是闰年

  • lengthOfMonth() int 这个月有多少天

  • lengthOfYear() int 该对象表示的年份有多少天(365或者366)

  • plusYears(long yearsToAdd) LocalDate 当前对象增加指定的年份数

  • plusMonths(long monthsToAdd) LocalDate 当前对象增加指定的月份数

  • plusWeeks(long weeksToAdd) LocalDate 当前对象增加指定的周数

  • plusDays(long daysToAdd) LocalDate 当前对象增加指定的天数

  • minusYears(long yearsToSubtract) LocalDate 当前对象减去指定的年数

  • minusMonths(long monthsToSubtract) LocalDate 当前对象减去注定的月数

  • minusWeeks(long weeksToSubtract) LocalDate 当前对象减去指定的周数

  • minusDays(long daysToSubtract) LocalDate 当前对象减去指定的天数

  • compareTo(ChronoLocalDate other) int 比较当前对象和other对象在时间上的大小,返回值如果为正,则当前对象时间较晚,

  • isBefore(ChronoLocalDate other) boolean 比较当前对象日期是否在other对象日期之前

  • isAfter(ChronoLocalDate other) boolean 比较当前对象日期是否在other对象日期之后

  • isEqual(ChronoLocalDate other) boolean 比较两个日期对象是否相等
    */
    public class DateUtils4Java8 {
    public static final String DATE_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_FORMAT_SHORT = "yyyy-MM-dd";

    public static final String DATE_FORMAT_COMPACT = "yyyyMMdd";

    public static final String DATE_FORMAT_COMPACTFULL = "yyyyMMddHHmmss";

    public static final String DATE_FORMAT_FULL_MSEL = "yyyyMMddHHmmssSSSS";

    public static final String DATE_YEAR_MONTH = "yyyyMM";

    public static final String DATE_FORMAT_FULL_MSE = "yyyyMMddHHmmssSSS";

/**
 * 获取系统当前日期
 *
 * @return
 */
public static Date getCurrentDate() {
    return new Date();
}

/**
 * 获取系统当前日期
 *
 * @return
 */
public static LocalDateTime getCurrentLocalDateTime() {
    return LocalDateTime.now();
}

/**
 * 根据时间格式返回对应的String类型的时间
 *
 * @param format
 * @return
 */
public static String getCurDateTime(String format) {
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
    String dataTime = now.format(dateTimeFormatter);
    return dataTime;
}

/**
 * 得到当前日期
 *
 * @return String 当前日期 yyyy-MM-dd HH:mm:ss格式
 * @author kevin
 */
public static String getCurDateTimeFull() {
    return getCurDateTime(DATE_FORMAT_FULL);
}


/**
 * 得到当前日期
 *
 * @return String 当前日期 yyyyMMddHHmmss格式
 * @author kevin
 */
public static String getCurDateTime1() {
    return getCurDateTime(DATE_FORMAT_FULL);
}

/**
 * 得到当前日期YYYYMM格式
 *
 * @return String 当前日期 yyyyMM格式
 * @author kevin
 */
public static String getCurDateYYYYMM() {
    return getCurDateTime(DATE_YEAR_MONTH);
}


/**
 * 得到当前日期
 *
 * @return String 当前日期 yyyyMMdd格式
 * @author kevin
 */
public static String getCurDateYYYYMMDD() {
    return getCurDateTime(DATE_FORMAT_COMPACT);
}

/**
 * 判断是否是今天
 *
 * @param strDate
 * @return
 */
public static boolean isCurrentDay(String strDate) {
    boolean bRet = false;
    LocalDate strLocalDate = LocalDate.parse(strDate);
    if (LocalDate.now().getYear() == strLocalDate.getYear()) {
        MonthDay monthDay = MonthDay.from(strLocalDate);
        MonthDay today = MonthDay.from(LocalDate.now());
        return monthDay.equals(today);
    }
    return bRet;
}

/**
 * 获取几小时后的时间
 *
 * @param hour
 * @param format
 * @return
 */
public static String getAfterDateTime(int hour, String format) {
    LocalTime localTime = LocalTime.now().plusHours(hour);
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
    String dataTime = localTime.format(dateTimeFormatter);
    return dataTime;
}


/**
 * 当前日期时间戳(yyyyMMddHHmmssSSSS)
 *
 * @return
 * @author liangxuekai
 */
public static String getTimeStamp() {
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT_FULL_MSEL);
    return now.format(dateTimeFormatter);
}

/**
 * 日期转字符串
 *
 * @return String
 * @author kevin
 */
public static String parseDateToString(Date thedate, String format) {
    if (thedate != null) {
        Instant instant = thedate.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        return localDateTime.format(dateTimeFormatter);
    }
    return null;
}

/**
 * parseDateToString(Date thedate, String format)的重载方法
 *
 * @param thedate
 * @return
 */
public static String parseDateToString(Date thedate) {
    // String format = "yyyy-MM-dd";
    return parseDateToString(thedate, DATE_FORMAT_FULL);
}

/**
 * 字符串转日期
 *
 * @return Date
 * @author kevin
 */
public static Date parseStringToDate(String thedate, String format) {
    DateFormat sdf = new SimpleDateFormat(format);
    Date dd1 = null;
    try {
        dd1 = sdf.parse(thedate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dd1;
}

/**
 * 由String型日期转成format形式String
 *
 * @param format1 原先格式
 * @param format2 转化格式
 * @return String
 * @author kevin
 */
public static String changeFormatDateString(String format1, String format2, String strDate) {
    if (strDate == null)
        return "";
    if (strDate.length() >= format1.length() && format1.length() >= format2.length()) {
        return parseDateToString(parseStringToDate(strDate, format1), format2);
    }
    return strDate;
}

/**
 * 得到当前日期的前N天时间 yyyymmdd
 *
 * @param format
 * @param day
 * @return
 */
public static String beforeNDaysDate(String format, int day) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
    if (day > 0) {
        return LocalDateTime.now().minusDays(day).format(dateTimeFormatter);
    }
    return null;
}

/**
 * 获得N个月后的日期
 * <p>
 * theDate 日期
 * <p>
 * int month 月数
 * <p>
 * format 格式
 */
public static String afterNMonthDate(String theDate, int month, String format) {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
    return LocalDateTime.parse(theDate,dateTimeFormatter)
            .plusMonths(month)
            .format(dateTimeFormatter);

}

/**
 * 得到N天后的日期
 *
 * @param theDate 某日期
 *                格式 yyyy-MM-dd
 * @param nDayNum N天
 * @return String N天后的日期
 * @author kevin
 */
public static String afterNDaysDate(String theDate, Integer nDayNum, String format) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);

    return LocalDateTime.parse(theDate,dateTimeFormatter)
            .plusDays(nDayNum)
            .format(dateTimeFormatter);
}

/**
 * 得到N小时后的日期
 *
 * @param theDate  时间
 * @param nHourNum N小时数
 * @param format   时间格式
 * @return
 */
public static String afterNHoursDate(String theDate, Integer nHourNum, String format) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
    return LocalDateTime.parse(theDate,dateTimeFormatter)
            .plusHours(nHourNum)
            .format(dateTimeFormatter);
}

/**
 * 得到N分钟后的日期
 *
 * @param theDate
 * @param nMinNum
 * @param format
 * @return
 */
public static String afterNMinsDate(String theDate, Integer nMinNum, String format) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
    return LocalDateTime.parse(theDate,dateTimeFormatter)
            .plusMinutes(nMinNum)
            .format(dateTimeFormatter);
}

/**
 * 得到N秒后的日期
 * @param theDate
 * @param nSecNum
 * @param format
 * @return
 */
public static String afterNSecondsDate(String theDate, Integer nSecNum, String format) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
    return LocalDateTime.parse(theDate,dateTimeFormatter)
            .plusSeconds(nSecNum)
            .format(dateTimeFormatter);
}

// 比较两个字符串格式日期大小,带格式的日期
public static boolean isBefore(String strdat1, String strdat2, String format) {
    try {
        Date dat1 = parseStringToDate(strdat1, format);
        Date dat2 = parseStringToDate(strdat2, format);
        return dat1.before(dat2);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

// 比较两个字符串格式日期大小,带格式的日期,返回int
public static long isBefore_int(String strdat1, String strdat2, String format) {
    long result = 0;
    try {
        Date dat1 = parseStringToDate(strdat1, format);
        Date dat2 = parseStringToDate(strdat2, format);
        return dat2.getTime() - dat1.getTime();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}


/*
 * 得到上一个月或者下一个月的日期
 */
public static String getDayafterMonth(String theDate, int month, String formatStr) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);
    return LocalDateTime.parse(theDate).plusMonths(month).format(dateTimeFormatter);
   /* Calendar now = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
    Date dat1 = parseStringToDate(theDate, formatStr);
    now.setTime(dat1);
    sdf.setTimeZone(TimeZone.getDefault());
    now.add(Calendar.MONTH, month);
    return sdf.format(now.getTime());*/
}

/**
 * 将秒转换为小时分秒等
 *
 * @param sec
 * @return
 */
public String changeTime(int sec) {
    String temp = "";
    if (sec < 60) {
        temp = "" + sec + "秒";
    } else if (sec < 3600) {
        temp = "" + sec / 60 + "分" + sec % 60 + "秒";
    } else {
        temp = "" + sec / 3600 + "小时" + (sec % 3600) / 60 + "分" + sec % 60 + "秒";
    }
    return temp;
}

/**
 * 方法描述:
 * 计算两个日期相差天数
 *
 * @param end   结束日期
 * @param start 开始日期
 * @return 作者:liangxuekai
 * 日期:2018 2018年1月31日
 */
public static int getSubDays(String end, String start) {
    LocalDate startDate = LocalDate.parse(start);
    LocalDate endDate = LocalDate.parse(end);
    Long between = ChronoUnit.DAYS.between(startDate, endDate);
    return between.intValue();
}


public static String getTimeDiff(Date time1, Date time2) throws Exception {
    long l = time1.getTime() - time2.getTime();
    String returnStr = "";
    long day = l / (24 * 60 * 60 * 1000);
    if (day > 0) {
        returnStr += (day + "天");
    }
    long hour = (l / (60 * 60 * 1000) - day * 24);
    if (hour > 0) {
        returnStr += (hour + "小时");
    }
    long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
    if (min > 0) {
        returnStr += (min + "分");
    }
    long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
    if (s > 0) {
        returnStr += (s + "秒");
    }
    return returnStr;
}

}`

相关文章
|
29天前
Mybatis+mysql动态分页查询数据案例——分页工具类(Page.java)
Mybatis+mysql动态分页查询数据案例——分页工具类(Page.java)
21 1
|
4月前
|
Java API
【零基础学Java】—数组工具类Arrays(十七)
【零基础学Java】—数组工具类Arrays(十七)
|
4月前
|
Java
【零基础学Java】—数学工具类Math(十八)
【零基础学Java】—数学工具类Math(十八)
|
4月前
|
安全 算法 Java
Java之并发工具类的详细解析
3. 并发工具类 3.1 并发工具类-Hashtable Hashtable出现的原因 : 在集合类中HashMap是比较常用的集合对象,但是HashMap是线程不安全的(多线程环境下可能会存在问题)。为了保证数据的安全性我们可以使用Hashtable,但是Hashtable的效率低下。
29 0
|
7月前
|
Java
Java操作时间工具类
Java操作时间工具类
49 0
|
29天前
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
15 1
|
4天前
|
安全 Java
深入理解 Java 多线程和并发工具类
【4月更文挑战第19天】本文探讨了Java多线程和并发工具类在实现高性能应用程序中的关键作用。通过继承`Thread`或实现`Runnable`创建线程,利用`Executors`管理线程池,以及使用`Semaphore`、`CountDownLatch`和`CyclicBarrier`进行线程同步。保证线程安全、实现线程协作和性能调优(如设置线程池大小、避免不必要同步)是重要环节。理解并恰当运用这些工具能提升程序效率和可靠性。
|
25天前
|
JSON Java 网络安全
Java使用hutool工具类发送网络请求
Java使用hutool工具类发送网络请求
41 0
|
2月前
|
Java Linux 数据安全/隐私保护
Java【代码 16】将word、excel文件转换为pdf格式和将pdf文档转换为image格式工具类分享(Gitee源码)aspose转换中文乱码问题处理
【2月更文挑战第3天】Java 将word、excel文件转换为pdf格式和将pdf文档转换为image格式工具类分享(Gitee源码)aspose转换中文乱码问题处理
99 0
|
2月前
|
安全 算法 Java
Java Collections工具类:常用方法与技巧
Java Collections工具类:常用方法与技巧