java中DateTime格式化通用时间


package com.freshjn.clzjn.market.property.platform.service.util;

import cn.hutool.core.date.DateUtil;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Months;

import java.math.BigDecimal;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.Locale;

/**
 * Created by wjq on 2021/10/8.
 */
public class DateUtils {
    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String YYYY_MM_DD = "yyyy-MM-dd";
    public static final String YYYY_MM = "yyyy-MM";
    public static final String UNDERLINE_YYYY_MM_DD = "yyyy_MM_dd";
    public static final String YYYYMM = "yyyyMM";
    public static final String YYYYMMDD = "yyyyMMdd";
    public static final String UNDERLINE_YYYY_MM = "yyyy_MM";

    public static final int SECOND_PER_MIN = 60;
    public static final int HOUR_PER_DAY = 24;
    public static final int MINUTES_PER_HOUR = 60;
    public static final int SECOND_PER_HOUR = MINUTES_PER_HOUR * SECOND_PER_MIN;
    public static final long SECOND_PER_DAY = HOUR_PER_DAY * MINUTES_PER_HOUR * SECOND_PER_MIN;

    /**
     * date格式化
     *
     * @param pattern
     * @return
     */
    public static String format(Instant instant, String pattern) {
        ZoneId zoneId = ZoneId.systemDefault();
        return format(instant, zoneId, pattern);
    }

    /**
     * getDateByTimeZone
     * 根据时区格式化date
     *
     * @param pattern
     * @return
     */
    public static String format(Instant instant, ZoneId zoneId, String pattern) {
        ZonedDateTime zonedDateTime = instant.atZone(zoneId);
        return format(zonedDateTime, pattern);
    }

    public static String format(ZonedDateTime zonedDateTime, String pattern) {
        return zonedDateTime.format(DateTimeFormatter.ofPattern(pattern, Locale.getDefault(Locale.Category.FORMAT)));
    }

    /**
     * 格式化当前时间
     *
     * @param pattern
     * @return
     */
    public static String formatNow(String pattern) {
        LocalDateTime localDateTime = LocalDateTime.now();
        return format(localDateTime, pattern);
    }

    /**
     * 格式化时间
     *
     * @param localDateTime
     * @param pattern
     * @return
     */
    public static String format(LocalDateTime localDateTime, String pattern) {
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * String类型时间转化成unix time
     *
     * @param time
     * @param pattern String 类型时间格式
     * @param zoneId  时区
     * @return 不正确的参数返回0
     */
    public static long strDateToUnixTime(String time, String pattern, ZoneId zoneId) {
        LocalDate localDate = LocalDate.parse(time, DateTimeFormatter.ofPattern(pattern));
        LocalDateTime localDateTime = localDate.atTime(0, 0, 0);
        return strToUnixTime(localDateTime, zoneId);
    }

    /**
     * String类型时间转化成unix time
     *
     * @param time
     * @param pattern String 类型时间格式
     * @param zoneId  时区
     * @return 不正确的参数返回0
     */
    public static long strTimeToUnixTime(String time, String pattern, ZoneId zoneId) {
        LocalDateTime localDateTime = LocalDateTime.parse(time, DateTimeFormatter.ofPattern(pattern));
        return strToUnixTime(localDateTime, zoneId);
    }

    /**
     * String类型时间转化成unix time  默认根据当前时区转换
     *
     * @param time
     * @param pattern String 类型时间格式
     * @return 不正确的参数返回0
     */

    public static long strToUnixTime(String time, String pattern) {
        return strTimeToUnixTime(time, pattern, ZoneId.systemDefault());
    }

    /**
     * LocalDateTime to seconds
     *
     * @param localDateTime
     * @param zoneId
     * @return
     */
    public static long strToUnixTime(LocalDateTime localDateTime, ZoneId zoneId) {
        ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
        return zonedDateTime.toEpochSecond();
    }

    /**
     * 获取一周的第几天
     *
     * @param zonedDateTime
     * @return
     */
    public static int dayOfWeek(ZonedDateTime zonedDateTime) {
        int day = zonedDateTime.getDayOfWeek().getValue();
        if (day < 0) {
            day = 0;
        }
        return day;
    }

    /**
     * 获取一月的第几天
     *
     * @param zonedDateTime
     * @return
     */
    public static int dayOfMonth(ZonedDateTime zonedDateTime) {
        int day = zonedDateTime.getDayOfMonth();
        return day;
    }

    public static int monthOfYear(ZonedDateTime zonedDateTime) {
        int monthValue = zonedDateTime.getMonthValue();
        return monthValue;
    }

    public static long getLastZeroDayOfMonth(long endTime, String timezone, int plushMonths) {
        ZonedDateTime zonedDateTime = getZonedDateTime(endTime, ZoneId.of(timezone));
        zonedDateTime = zonedDateTime.withHour(0).withMinute(0).withSecond(0);
        return lastDayOfMonth(zonedDateTime, plushMonths);
    }

    public static long getFirstZeroDayOfMonth(long endTime, String timezone, int plushMonths) {
        ZonedDateTime zonedDateTime = getZonedDateTime(endTime, ZoneId.of(timezone));
        zonedDateTime = zonedDateTime.withHour(0).withMinute(0).withSecond(0);
        return firstDayOfMonth(zonedDateTime, plushMonths);
    }

    public static long getFirstDayOfMonth(long endTime, String timezone, int plushMonths) {
        ZonedDateTime zonedDateTime = getZonedDateTime(endTime, ZoneId.of(timezone));
        return firstDayOfMonth(zonedDateTime, plushMonths);
    }

    public static long firstDayOfMonth(ZonedDateTime zonedDateTime, int plushMonths) {
        return zonedDateTime.plusMonths(plushMonths).with(TemporalAdjusters.firstDayOfMonth()).toEpochSecond();
    }

    private static long lastDayOfMonth(ZonedDateTime zonedDateTime, int plushMonths) {
        return zonedDateTime.plusMonths(plushMonths).with(TemporalAdjusters.lastDayOfMonth()).toEpochSecond();
    }

    public static long plusDaysTime(ZonedDateTime zonedDateTime, int days, int hour, int min, int second) {
        zonedDateTime = zonedDateTime.plus(days, ChronoUnit.DAYS)
                .withHour(hour)
                .withMinute(min)
                .withSecond(second)
                .withNano(0);
        return zonedDateTime.toInstant().getEpochSecond();
    }

    public static long plushDaysTime(String ymd, ZoneId zoneId, String formatter, int days) {
        LocalDateTime localDate = LocalDateTime.parse(ymd, DateTimeFormatter.ofPattern(formatter));
        localDate = localDate.plusDays(days);
        return localDate.atZone(zoneId).toEpochSecond();
    }

    public static long plusWeeksTime(ZonedDateTime zonedDateTime, int week, int hour, int min, int second) {
        zonedDateTime = zonedDateTime.plus(week, ChronoUnit.WEEKS)
                .withHour(hour)
                .withMinute(min)
                .withSecond(second)
                .withNano(0);
        return zonedDateTime.toInstant().getEpochSecond();
    }

    public static long plusMonthsTime(ZonedDateTime zonedDateTime, int month, int day, int hour, int min, int second) {
        zonedDateTime = zonedDateTime.plus(month, ChronoUnit.MONTHS)
                .withDayOfMonth(day)
                .withHour(hour)
                .withMinute(min)
                .withSecond(second)
                .withNano(0);
        return zonedDateTime.toInstant().getEpochSecond();
    }

    public static final Date long2Date(long time, String timeZone) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(time), ZoneId.of(timeZone));
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    // 获取前count天
    public static final Date getAddCountDay(final int count, Instant instant) {
        instant = instant.plus(count, ChronoUnit.DAYS);
        return Date.from(instant);
    }

    public static int intervalDays(long beforeTimestamp, long afterTimestamp) {
        int day = (int) ((afterTimestamp - beforeTimestamp) / (SECOND_PER_MIN * MINUTES_PER_HOUR * HOUR_PER_DAY));
        return day;
    }

    public static float intervalHours(long beforeTimestamp, long afterTimestamp) {
        String time1 = String.valueOf((afterTimestamp - beforeTimestamp));
        String time2 = String.valueOf((SECOND_PER_MIN * MINUTES_PER_HOUR));
        BigDecimal bd1 = new BigDecimal(time1);
        BigDecimal bd2 = new BigDecimal(time2);
        float hour = bd1.divide(bd2, 1, BigDecimal.ROUND_HALF_UP).floatValue();
        return hour;
    }

    public static ZonedDateTime getZonedDateTime(long timestamp, ZoneId zoneId) {
        ZonedDateTime zonedDateTime = Instant.ofEpochSecond(timestamp).atZone(zoneId);
        return zonedDateTime;
    }

    public static long getTimestamp() {
        return Instant.now().getEpochSecond();
    }

    public static long getZeroByTimeStamp(long timestamp, ZoneId zoneId) {
        ZonedDateTime zonedDateTime = Instant.ofEpochSecond(timestamp).atZone(zoneId);
        zonedDateTime = zonedDateTime.withMinute(0).withSecond(0);
        return zonedDateTime.toEpochSecond();
    }

    public static int getMonthSpace(final Date beforeDate, final Date afterDate) {
        LocalDateTime beforeLocalDateTime = LocalDateTime.ofInstant(beforeDate.toInstant(), ZoneId.systemDefault());
        LocalDateTime afterLocalDateTime = LocalDateTime.ofInstant(afterDate.toInstant(), ZoneId.systemDefault());
        int year = afterLocalDateTime.getYear() - beforeLocalDateTime.getYear();
        int afterMonth = afterLocalDateTime.getMonthValue();
        int beforeMonth = beforeLocalDateTime.getMonthValue();
        int result = (afterMonth - beforeMonth) + 12 * year;
        return Math.abs(result);
    }

    /**
     * 判断时区是否为半时区
     *
     * @param zoneId
     * @return
     */
    public static boolean isHalfZone(String zoneId) {
        ZoneId zone = ZoneId.of(zoneId);
        int seconds = zone.getRules().getOffset(LocalDateTime.now()).getTotalSeconds() % SECOND_PER_HOUR;
        return (seconds != 0);
    }

    public static long getZeroByTimeStampAndZoneId(long timestamp, ZoneId zoneId) {
        ZonedDateTime zonedDateTime = Instant.ofEpochSecond(timestamp).atZone(zoneId);
        zonedDateTime = zonedDateTime.withHour(0).withMinute(0).withSecond(0);

        return zonedDateTime.toEpochSecond();
    }

    public static Integer getIntervalMonths(DateTime startDateTime, DateTime endDateTime){
        startDateTime = startDateTime.withDayOfMonth(1).withHourOfDay(0).withMinuteOfHour(0).withMillisOfSecond(0).withSecondOfMinute(0);
        endDateTime = endDateTime.withDayOfMonth(1).withHourOfDay(0).withMinuteOfHour(0).withMillisOfSecond(0).withSecondOfMinute(0);

        int months = Months.monthsBetween(startDateTime, endDateTime).getMonths();
        return months;
    }

    public static void main(String[] args) {
        String timezone = "Asia/Hong_Kong";
        String formatter = YYYY_MM_DD_HH_MM_SS;
        //格式化当前系统时间
        String format = format(Instant.now(), formatter);
        System.out.println(format);
        //以当前系统时间为基础,格式化带时区的时间
        String format1 = format(Instant.now(), ZoneId.of(timezone), formatter);
        System.out.println(format1);
        //LocalDateTiem格式化当前时间
        String format2 = format(Instant.now().atZone(ZoneId.of(timezone)).toLocalDateTime(), formatter);
        System.out.println(format2);
        //ZoneDateTime格式化当前时间
        String format3 = format(ZonedDateTime.ofInstant(Instant.now(), ZoneId.of(timezone)), formatter);
        System.out.println(format3);
        //根据8时区转换本机系统时间戳(2021-03-26 16:00:00)
        long l1 = strDateToUnixTime("2021-03-27", YYYY_MM_DD, ZoneId.of(timezone));
        System.out.println(l1);
        //根据8时区转换本机系统时间戳(2021-03-26 08:00:00)
        long l2 = strTimeToUnixTime("2021-03-26 16:00:00", YYYY_MM_DD_HH_MM_SS, ZoneId.of(timezone));
        System.out.println(l2);
        //根据当前时间格式字符串转换本机时间戳
        long l = strToUnixTime("2021-03-26 16:00:00", formatter);
        System.out.println(l);
        //根据时区求当前时间戳
        long l3 = strToUnixTime(Instant.now().atZone(ZoneId.systemDefault()).toLocalDateTime(), ZoneId.of(timezone));
        System.out.println(l3);
        //获取星期几
        int i = dayOfWeek(ZonedDateTime.now());
        System.out.println(i);
        //获得一月的第几天
        int i1 = dayOfMonth(ZonedDateTime.now());
        System.out.println(i1);
        //获取一年的第几个月
        int i2 = monthOfYear(ZonedDateTime.now());
        System.out.println(i2);
        //下一个月的最后一天0点时间戳
        long utc = getLastZeroDayOfMonth(1616750000, "UTC", 1);
        System.out.println(utc);
        //下一个月的第一天0点时间戳
        long utc2 = getFirstZeroDayOfMonth(1616750000, "UTC", 1);
        System.out.println(utc2);
        //下一个月1号的时间戳,时间跟endtime相同
        long utc3 = getFirstDayOfMonth(1616750000, "UTC", 1);
        System.out.println(utc3);
        //下一个月1号的时间戳,时间跟当前时间相同
        long l4 = firstDayOfMonth(ZonedDateTime.now(), 1);
        System.out.println(l4);
        //下一个月最后一天的时间戳,时间跟当前时间相同
        long l5 = lastDayOfMonth(ZonedDateTime.now(), 1);
        System.out.println(l5);
        //当前日期加两天,时间是 01:10:10
        long l6 = plusDaysTime(ZonedDateTime.now(), 2, 1, 10, 10);
        System.out.println(l6);
        //当前时间加上两天从0点开始
        long l7 = plushDaysTime("2021-03-26 16:00:00", ZoneId.systemDefault(), formatter, 2);
        System.out.println(l7);
        //当前日期加上1周,时间是 01:10:10
        long l8 = plusWeeksTime(ZonedDateTime.now(), 1, 1, 10, 10);
        System.out.println(l8);
        //当前时间的月加上1开始第1天开始的01:10:10
        long l9 = plusMonthsTime(ZonedDateTime.now(), 1, 1, 10, 10, 10);
        System.out.println(l9);
        //当前时区的转换为date对象
        Date date = long2Date(System.currentTimeMillis() / 1000, timezone);
        System.out.println(date);
        //加上一天转换了date对象
        Date addCountDay = getAddCountDay(1, Instant.now());
        System.out.println(addCountDay);
        //跨了多少天,还没过中午12点算一天
        int i3 = intervalDays(1617271810, 1616850390);
        System.out.println(i3);
        //垮了多少个小时
        float v = intervalHours(1616868390, 1616850390);
        System.out.println(v);
        //获取ZoneDateTime
        ZonedDateTime zonedDateTime = getZonedDateTime(1616868390, ZoneId.systemDefault());
        System.out.println(zonedDateTime);
        //获取时间戳
        long timestamp = getTimestamp();
        System.out.println(timestamp);
        //从当前小时开始的时间戳
        long zeroByTimeStamp = getZeroByTimeStamp(1616868390, ZoneId.systemDefault());
        System.out.println(zeroByTimeStamp);
        Date date1 = new Date();
        Date date2 = new Date();
        //根据date计算垮了多少个月
        int monthSpace = getMonthSpace(date1, date2);
        System.out.println(monthSpace);
        //是否是半时区
        boolean halfZone = isHalfZone(timezone);
        System.out.println(halfZone);
        //当前时间戳的0时区0点时间戳
        long zeroByTimeStampAndZoneId = getZeroByTimeStampAndZoneId(1616869439, ZoneId.systemDefault());
        System.out.println(zeroByTimeStampAndZoneId);
        //跨月数
        DateTime startDateTime = new DateTime(1614431190 * 1000).withZone(DateTimeZone.UTC);
        DateTime endDateTime = new DateTime( 1616803200 * 1000).withZone(DateTimeZone.UTC);
        Integer intervalMonths = getIntervalMonths(startDateTime, endDateTime);
        System.out.println(intervalMonths);

        LocalDate today = LocalDate.now(ZoneId.of("GMT+8"));
        LocalDate firstDay = LocalDate.of(today.getYear(), today.getMonth(), 1);
        LocalDate lastDay = today.with(TemporalAdjusters.lastDayOfMonth());

        LocalDateTime startTime = LocalDateTime.of(firstDay, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(lastDay, LocalTime.MAX);

        System.out.println(DateUtil.format(startTime,"yyyy-MM-dd"));
        System.out.println(DateUtil.format(endTime,"yyyy-MM-dd"));

    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM