java常用日期操作

java常用日期操作


1,获取几天前的日期

	/**
     * 获取几天前的日期
     *
     * @param date 日期
     * @param day  天
     * @return Date
     */
    public static Date getDateBefore(Date date, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

2,获取几天后的日期

	/**
     * 获取几天后的日期
     *
     * @param date 日期
     * @param day  天
     * @return Date
     */
    public static Date getDateAfter(Date date, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.getTime();
    }

3,获取今日零点Date

    /**
     * 获取今日零点Date
     *
     * @return Date
     */
    public static java.util.Date getTodayZero() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        return calendar.getTime();
    }

4,UTC格式时间转换为sql.Timestamp

    /**
     * UTC格式时间转换为sql.Timestamp
     *
     * @param text    UTC+0时间
     * @param pattern 格式化
     * @return java.sql.Timestamp
     */
    public static java.sql.Timestamp utc2SqlTimestamp(String text, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime parse = LocalDateTime.parse(text, dateTimeFormatter);
        long longTime = LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        return new Timestamp(longTime);
    }

5,LocalDateTime转换为格式化字符串

    /**
     * LocalDateTime转换为格式化字符串
     *
     * @param localDateTime LocalDateTime
     * @param pattern       格式化
     * @return String
     */
    public static String localDateTime2Str(LocalDateTime localDateTime, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return localDateTime.format(formatter);
    }

你可能感兴趣的:(java,date,日期,时间)