game-api/ff-base/src/main/java/com/ff/base/utils/DateUtils.java

998 lines
35 KiB
Java
Raw Normal View History

2025-02-11 15:27:15 +08:00
package com.ff.base.utils;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
/**
*
*
* @author ff
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
public static String HHMMSS = "HH:mm:ss";
public static String DAY_START_TIME = "00:00:00";
public static String DAY_END_TIME = "23:59:59";
public static final String ISO_8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
public static final String ISO_8601_FORMAT_Z = "yyyy-MM-dd'T'HH:mm:ss'Z'";
2025-02-11 15:27:15 +08:00
/**
* Date
*
* @return Date()
*/
public static Long getNowDate() {
return Instant.now().toEpochMilli();
}
/**
*
*
* @return {@link Long }
*/
public static Date getCurrentDate() {
return new Date();
}
/**
* , yyyy-MM-dd
*
* @return String
*/
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}
public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* // 2018/08/08
*/
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
/**
* // 20180808
*/
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
/**
*
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
*
*/
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
/**
*
*/
public static int differentDaysByMillisecond(Date date1, Date date2) {
return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
}
/**
*
*
* @param endDate
* @param startTime
* @return //
*/
public static String timeDistance(Date endDate, Date startTime) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - startTime.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return day + "天" + hour + "小时" + min + "分钟";
}
/**
* LocalDateTime ==> Date
*/
public static Date toDate(LocalDateTime temporalAccessor) {
ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant());
}
/**
* yymmd
*
* @return {@link String }
*/
public static String getFormattedDate() {
ZonedDateTime nowUtcMinus4 = ZonedDateTime.now(ZoneId.of("UTC-4"));
String year = String.format("%02d", nowUtcMinus4.getYear() % 100);
String month = String.format("%02d", nowUtcMinus4.getMonthValue());
String day = String.valueOf(nowUtcMinus4.getDayOfMonth());
return year + month + day;
}
/**
* gmt4
*
* @param date
* @return {@link String }
*/
public static String formatDateToGMT4(Date date) {
// 将 Date 转换为 ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of("GMT-4"));
// 定义日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
// 格式化并返回字符串
return zdt.format(formatter);
}
/**
*
*
* @param timestamp
* @param format yyyy-MM-dd'T'HH:mm:ssXXX
* @param timeZone GMT+8UTC
* @return
*/
public static String convertTimestampToFormattedDate(long timestamp, String format, String timeZone) {
// 创建日期格式化对象
SimpleDateFormat sdf = new SimpleDateFormat(format);
// 设置时区为GMT+8
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
// 转换为 Date 对象
Date date = new Date(timestamp);
// 返回格式化后的时间字符串
return sdf.format(date);
}
/**
*
*
* @param timestampInMillis
* @param timeZone America/New_York
* @param format yyyy-MM-dd HH:mm:ss
* @return
*/
public static String convertTimeZone(long timestampInMillis, String timeZone, String format) {
// 将毫秒时间戳转换为 Instant
Instant instant = Instant.ofEpochMilli(timestampInMillis);
// 将 UTC 时间转换为指定时区的时间
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of(timeZone));
// 格式化输出为指定格式的时间字符串
return zonedDateTime.format(DateTimeFormatter.ofPattern(format));
}
2025-02-11 15:27:15 +08:00
/**
* LocalDate ==> Date
*/
public static Date toDate(LocalDate temporalAccessor) {
LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant());
}
/**
*
*
* @param timestampMillis
* @param minutes
* @return long
*/
public static long addOrSubtractMinutes(long timestampMillis, int minutes) {
// 将分钟转换为毫秒,并加到时间戳上
return timestampMillis + minutes * 60 * 1000L;
}
/**
*
*
* @param timestampDay
* @param day
* @return long
*/
public static long addOrSubtractDay(long timestampDay, int day) {
// 将分钟转换为毫秒,并加到时间戳上
return timestampDay + day * 60 * 1000L * 60 * 24;
}
/**
*
*
* @return
*/
public static Long getDayStart(Calendar calendar) {
// 设置时间为当天的 00:00:00
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
*
*
* @param timestamp
* @param timeZoneId
* @return
*/
public static Long getDayStart(long timestamp, String timeZoneId) {
ZoneId zoneId = ZoneId.of(timeZoneId);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(java.time.Instant.ofEpochMilli(timestamp), zoneId);
LocalDate localDate = zonedDateTime.toLocalDate();
LocalDateTime startOfDay = localDate.atStartOfDay();
ZonedDateTime startOfDayZoned = startOfDay.atZone(zoneId);
return startOfDayZoned.toInstant().toEpochMilli();
}
/**
*
*
* @return
*/
public static Long getDayEnd(Calendar calendar) {
// 设置时间为当天的 23:59:59
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
*
*
* @param timestamp
* @param timeZoneId
* @return
*/
public static Long getDayEnd(long timestamp, String timeZoneId) {
ZoneId zoneId = ZoneId.of(timeZoneId);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(java.time.Instant.ofEpochMilli(timestamp), zoneId);
LocalDate localDate = zonedDateTime.toLocalDate();
LocalDateTime endOfDay = localDate.atTime(23, 59, 59, 999999999);
ZonedDateTime endOfDayZoned = endOfDay.atZone(zoneId);
return endOfDayZoned.toInstant().toEpochMilli();
}
/**
*
*
* @return
*/
public static Long getYesterdayStart() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// 回溯一天
calendar.add(Calendar.DAY_OF_MONTH, -1);
// 设置时间为当天的 00:00:00
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
*
*
* @return
*/
public static Long getYesterdayEnd() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// 回溯一天
calendar.add(Calendar.DAY_OF_MONTH, -1);
// 设置时间为当天的 23:59:59
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
*
*
* @return
*/
public static Long getLastWeekBegin() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// 计算上周的起始日期(周一)
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.add(Calendar.WEEK_OF_YEAR, -1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
*
*
* @return
*/
public static Long getLastWeekEnd() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// 计算上周的结束日期(周日)
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
*
*
* @return
*/
public static Long getWeekBegin(Calendar calendar) {
// 设置一周的第一天为星期一
calendar.setFirstDayOfWeek(Calendar.MONDAY);
// 获取当前日期在本周的位置
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
// 计算需要回溯的天数
int daysToSubtract = (dayOfWeek == Calendar.SUNDAY ? 6 : dayOfWeek - 2);
calendar.add(Calendar.DAY_OF_MONTH, -daysToSubtract);
// 设置时间为当天的 00:00:00
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
*
*
* @return
*/
public static Long getWeekEnd(Calendar calendar) {
// 设置一周的第一天为星期一
calendar.setFirstDayOfWeek(Calendar.MONDAY);
// 获取当前日期在本周的位置
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
// 计算需要前进的天数
int daysToAdd = (dayOfWeek == Calendar.SUNDAY ? 0 : 7 - (dayOfWeek - 1));
calendar.add(Calendar.DAY_OF_MONTH, daysToAdd);
// 设置时间为当天的 23:59:59
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
*
*
* @return
*/
public static Long getMonthStart(Calendar calendar) {
// 设置时间为当月的第一天
calendar.set(Calendar.DAY_OF_MONTH, 1);
// 设置时间为当天的 00:00:00
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
*
*
* @return
*/
public static Long getMonthEnd(Calendar calendar) {
// 设置时间为当月的最后一天
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
// 设置时间为当天的 23:59:59
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
*
*
* @return
*/
public static Long getLastMonthStart() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// 计算上个月的起始日期1号
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
*
*
* @return
*/
public static Long getLastMonthEnd() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.add(Calendar.MONTH, -1); // 回退一个月
// 计算上个月的结束日期(最后一天)
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); // 设置日期为当月最后一天
calendar.set(Calendar.HOUR_OF_DAY, 23); // 设置小时为23
calendar.set(Calendar.MINUTE, 59); // 设置分钟为59
calendar.set(Calendar.SECOND, 59); // 设置秒为59
calendar.set(Calendar.MILLISECOND, 999); // 设置毫秒为999
return calendar.getTimeInMillis();
}
/**
* A B C
*
* @param timestampA A
* @param timestampB B
* @param timestampC C
* @return true A B false A C
*/
public static boolean isCloserToB(long timestampA, long timestampB, long timestampC) {
long diffAB = Math.abs(timestampA - timestampB);
long diffAC = Math.abs(timestampA - timestampC);
return diffAB < diffAC;
}
/**
*
*
* @param utcTimestamp utc
* @param date
* @param timeZonId
* @return
*/
public static long getTomorrowTimeByZonId(long utcTimestamp, Date date, String timeZonId) {
SimpleDateFormat sdf = new SimpleDateFormat(HHMMSS);
String format = sdf.format(date);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(HHMMSS);
LocalTime localTime = LocalTime.parse(format, timeFormatter);
// 将时间戳转换为 Instant
Instant instant = Instant.ofEpochMilli(addOrSubtractDay(utcTimestamp, 1));
ZoneId zoneId = ZoneId.of(timeZonId);
LocalDate localDate = instant.atZone(zoneId).toLocalDate();
LocalDateTime tomorrowDrawStartTime = localDate.atTime(localTime);
return tomorrowDrawStartTime.atZone(zoneId).toInstant().toEpochMilli();
}
/**
*
*
* @param date
* @param timeZonId
* @return
*/
public static long getTodayTimeByZonId(Date date, String timeZonId) {
// 获取今日指定时间后的时间戳
SimpleDateFormat sdf = new SimpleDateFormat(HHMMSS);
String format = sdf.format(date);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(HHMMSS);
LocalTime localTime = LocalTime.parse(format, timeFormatter);
LocalDate currentDate = LocalDate.now();
LocalDateTime todayDrawStartTime = currentDate.atTime(localTime);
ZoneId zoneId = ZoneId.of(timeZonId);
return todayDrawStartTime.atZone(zoneId).toInstant().toEpochMilli();
}
/**
*
*
* @param dayOfWeek 1-7
* @param date Date
* @return UTC
*/
public static long getNextWeekTimestamp(int dayOfWeek, Date date, ZoneId zoneId) {
// 将Date对象转换为LocalDateTime对象
SimpleDateFormat sdf = new SimpleDateFormat(HHMMSS);
String format = sdf.format(date);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(HHMMSS);
LocalTime localTime = LocalTime.parse(format, timeFormatter);
// 获取当前日期时间
ZonedDateTime now = ZonedDateTime.now(zoneId);
// 找到本周的周几
ZonedDateTime startOfWeek = now.with(dayOfWeek < now.getDayOfWeek().getValue() ? TemporalAdjusters.previousOrSame(DayOfWeek.of(dayOfWeek)) : TemporalAdjusters.nextOrSame(DayOfWeek.of(dayOfWeek)));
// 加上一个完整的星期,得到下周的周几
ZonedDateTime nextWeekStart = startOfWeek.plusWeeks(1);
// 设置指定的时间
ZonedDateTime targetDateTime = nextWeekStart.withHour(localTime.getHour()).withMinute(localTime.getMinute()).withSecond(localTime.getSecond()).withNano(0);
// 转换为时间戳(毫秒)
return targetDateTime.toInstant().toEpochMilli();
}
/**
*
*
* @param dayOfWeek 1-7
* @param date Date
* @return
*/
public static long getCurrentWeekTimestamp(int dayOfWeek, Date date, ZoneId zoneId) {
// 将Date对象转换为LocalDateTime对象
SimpleDateFormat sdf = new SimpleDateFormat(HHMMSS);
String format = sdf.format(date);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(HHMMSS);
LocalTime localTime = LocalTime.parse(format, timeFormatter);
// 获取当前日期时间
LocalDateTime now = LocalDateTime.now();
// 获取当前周的指定周几的日期时间
LocalDateTime currentWeekDateTime = now.with(dayOfWeek < now.getDayOfWeek().getValue() ? TemporalAdjusters.previousOrSame(DayOfWeek.of(dayOfWeek)) : TemporalAdjusters.nextOrSame(DayOfWeek.of(dayOfWeek)))
.withHour(localTime.getHour())
.withMinute(localTime.getMinute())
.withSecond(localTime.getSecond())
.withNano(0);
// 将LocalDateTime转换为ZonedDateTime使用UTC时区
ZonedDateTime zonedDateTime = currentWeekDateTime.atZone(zoneId);
// 将ZonedDateTime转换为时间戳毫秒
return zonedDateTime.toInstant().toEpochMilli();
}
/**
*
*
* @param dayOfMonth 1-31
* @param date Date
* @param month
* @return
*/
public static long getNextMonthTimestamp(int dayOfMonth, Date date, ZoneId zoneId, int month) {
// 将Date对象转换为LocalDateTime对象
SimpleDateFormat sdf = new SimpleDateFormat(HHMMSS);
String format = sdf.format(date);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(HHMMSS);
LocalTime localTime = LocalTime.parse(format, timeFormatter);
// 获取当前日期时间
LocalDateTime now = LocalDateTime.now();
// 获取下个月的年份和月份
YearMonth nextMonth = YearMonth.from(now).plusMonths(month);
int maxDayNum = nextMonth.lengthOfMonth();
if (dayOfMonth > maxDayNum) {
dayOfMonth = maxDayNum;
}
// 创建下个月指定日的LocalDateTime对象
LocalDateTime nextMonthDateTime = LocalDateTime.of(nextMonth.getYear(), nextMonth.getMonth(), dayOfMonth,
localTime.getHour(), localTime.getMinute(), localTime.getSecond(), 0);
// 将LocalDateTime转换为ZonedDateTime使用UTC时区
ZonedDateTime zonedDateTime = nextMonthDateTime.atZone(zoneId);
// 将ZonedDateTime转换为时间戳毫秒
return zonedDateTime.toInstant().toEpochMilli();
}
/**
*
*
* @param dayOfMonth 1-31
* @param date Date
* @return
*/
public static long getCurrentMonthTimestamp(int dayOfMonth, Date date, ZoneId zoneId) {
// 将Date对象转换为LocalDateTime对象
SimpleDateFormat sdf = new SimpleDateFormat(HHMMSS);
String format = sdf.format(date);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(HHMMSS);
LocalTime localTime = LocalTime.parse(format, timeFormatter);
// 获取当前日期时间
LocalDateTime now = LocalDateTime.now();
// 获取本月的年份和月份
YearMonth currentMonth = YearMonth.from(now);
int maxDayNum = currentMonth.lengthOfMonth();
if (dayOfMonth > maxDayNum) {
dayOfMonth = maxDayNum;
}
// 创建本月指定日的LocalDateTime对象
LocalDateTime currentMonthDateTime = LocalDateTime.of(currentMonth.getYear(), currentMonth.getMonth(), dayOfMonth,
localTime.getHour(), localTime.getMinute(), localTime.getSecond(), 0);
// 将LocalDateTime转换为ZonedDateTime使用UTC时区
ZonedDateTime zonedDateTime = currentMonthDateTime.atZone(zoneId);
// 将ZonedDateTime转换为时间戳毫秒
return zonedDateTime.toInstant().toEpochMilli();
}
/**
* UTC0
*
* @param timeZoneId id
* @param timestamp
* @return UTC0
*/
public static long covertToUTCtimestamp(String timeZoneId, long timestamp) {
// 将时间戳转换为 Instant 对象
Instant instant = Instant.ofEpochMilli(timestamp);
// 使用指定的时区将 Instant 对象转换为 ZonedDateTime 对象
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of(timeZoneId));
ZonedDateTime zonedDateTime1 = zonedDateTime.withZoneSameLocal(ZoneOffset.UTC);
// 将 ZonedDateTime 对象转换为 UTC0 时区的 Instant 对象
// 获取 UTC0 时区的时间戳(以毫秒为单位)
return zonedDateTime1.toInstant().toEpochMilli();
}
/**
* UTC
*
* @param timeZoneId id
* @param timestamp
* @return
*/
public static long covertUTCTotimeZonetimestamp(String timeZoneId, long timestamp) {
// 将时间戳转换为 Instant 对象
Instant instant = Instant.ofEpochMilli(timestamp);
// 使用指定的时区将 Instant 对象转换为 ZonedDateTime 对象
ZonedDateTime zonedDateTime = instant.atZone(ZoneOffset.UTC);
ZonedDateTime zonedDateTime1 = zonedDateTime.withZoneSameLocal(ZoneId.of(timeZoneId));
// 获取 指定 时区的时间戳(以毫秒为单位)
return zonedDateTime1.toInstant().toEpochMilli();
}
/**
* 0
*
* @param timestamp
* @param timeZone
* @return
*/
public static boolean isMidnight(long timestamp, TimeZone timeZone) {
Calendar calendar = Calendar.getInstance(timeZone);
calendar.setTimeInMillis(timestamp);
return calendar.get(Calendar.HOUR_OF_DAY) == 0 &&
calendar.get(Calendar.MINUTE) == 0 &&
calendar.get(Calendar.SECOND) == 0 &&
calendar.get(Calendar.MILLISECOND) == 0;
}
/**
* 0
*
* @param timestamp
* @param timeZone
* @return 0
*/
public static boolean isMondayMidnight(long timestamp, TimeZone timeZone) {
Calendar calendar = Calendar.getInstance(timeZone);
calendar.setTimeInMillis(timestamp);
return isMidnight(timestamp, timeZone) && calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY;
}
/**
* ISO 8601
*
* @param isoDate ISO 8601 "2025-05-10T08:23:34Z"
* @return Unix epoch
*/
public static long convertToMilliseconds(String isoDate) {
Instant instant = Instant.parse(isoDate);
return instant.toEpochMilli();
}
/**
* ZoneId TimeZone
*
* @param zoneId ZoneId
* @return TimeZone
*/
public static TimeZone zoneIdToTimeZone(ZoneId zoneId) {
return TimeZone.getTimeZone(zoneId.getId());
}
/**
* UTC
*
* @param dayOfWeek 1-717
* @return UTC
*/
public static Map<String, Object> getStartAndEndUTCTimestampOfDayOfWeek(int dayOfWeek) {
if (dayOfWeek < 1 || dayOfWeek > 7) {
throw new IllegalArgumentException("dayOfWeek must be between 1 and 7");
}
// 获取当前日期
LocalDate today = LocalDate.now(ZoneOffset.UTC);
// 计算本周的开始日期(星期一)
LocalDate monday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
// 计算指定星期几的日期
LocalDate targetDay = monday.plusDays(dayOfWeek - 1);
// 计算指定星期几的开始时间00:00:00 UTC
ZonedDateTime startOfDay = targetDay.atStartOfDay(ZoneOffset.UTC);
// 计算指定星期几的结束时间23:59:59 UTC
ZonedDateTime endOfDay = targetDay.atTime(LocalTime.MAX).atZone(ZoneOffset.UTC);
// 获取开始和结束时间戳
long startTimestamp = startOfDay.toInstant().toEpochMilli();
long endTimestamp = endOfDay.toInstant().toEpochMilli();
Map<String, Object> map = new HashMap<>();
map.put("beginTime", startTimestamp);
map.put("endTime", endTimestamp);
return map;
}
/**
* UTC
*
* @param dayOfMonth 1-31
* @return UTCMap"beginTime""endTime"
*/
public static Map<String, Object> getStartAndEndUTCTimestampOfDayOfMonth(int dayOfMonth) {
// 获取当前日期
LocalDate today = LocalDate.now(ZoneOffset.UTC);
// 获取本月的年份和月份
YearMonth currentMonth = YearMonth.from(today);
int maxDayNum = currentMonth.lengthOfMonth();
if (dayOfMonth > maxDayNum) {
dayOfMonth = maxDayNum;
}
// 获取当前年份和月份
int year = today.getYear();
int month = today.getMonthValue();
// 构建指定月几号的日期
LocalDate targetDay;
try {
targetDay = LocalDate.of(year, month, dayOfMonth);
} catch (DateTimeException e) {
throw new IllegalArgumentException("Invalid dayOfMonth for the current month", e);
}
// 计算指定月几号的开始时间00:00:00 UTC
ZonedDateTime startOfDay = targetDay.atStartOfDay(ZoneOffset.UTC);
// 计算指定月几号的结束时间23:59:59 UTC
ZonedDateTime endOfDay = targetDay.atTime(LocalTime.MAX).atZone(ZoneOffset.UTC);
// 获取开始和结束时间戳
long startTimestamp = startOfDay.toInstant().toEpochMilli();
long endTimestamp = endOfDay.toInstant().toEpochMilli();
Map<String, Object> map = new HashMap<>();
map.put("beginTime", startTimestamp);
map.put("endTime", endTimestamp);
return map;
}
/**
*
*
* @param timestamp1
* @param timestamp2
* @return truefalse
*/
public static boolean isSameDay(long timestamp1, long timestamp2) {
// 将时间戳转换为 LocalDate
LocalDate date1 = Instant.ofEpochMilli(timestamp1)
.atZone(ZoneId.systemDefault()) // 使用系统默认时区
.toLocalDate();
LocalDate date2 = Instant.ofEpochMilli(timestamp2)
.atZone(ZoneId.systemDefault()) // 使用系统默认时区
.toLocalDate();
// 比较日期部分是否相同
return date1.isEqual(date2);
}
/**
* UTC java.util.Date
*
* @return java.util.Date UTC
*/
public static Date getUTCDate() {
// 获取 UTC 时区的当前时间
ZonedDateTime utcTime = ZonedDateTime.now(ZoneId.of("UTC"));
// 提取 UTC 时区的日期部分
ZonedDateTime utcDateTime = utcTime.toLocalDate().atStartOfDay(ZoneId.of("UTC"));
// 将 ZonedDateTime 转换为 java.util.Date
return Date.from(utcDateTime.toInstant());
}
/**
* LocalTime Date
*
* @param localTime LocalTime
* @return Date
*/
public static Date convertToDate(LocalTime localTime) {
// 使用当前日期作为参考日期
LocalDate today = LocalDate.now();
// 将 LocalTime 和 LocalDate 结合成 LocalDateTime
LocalDateTime localDateTime = LocalDateTime.of(today, localTime);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = localDateTime.format(formatter);
// 将 LocalDateTime 转换为 Date
return DateUtils.parseDate(format);
}
/**
*
*
* @param value
* @param minValue
* @param maxValue
* @return
*/
public static boolean isBetween(Long value, Long minValue, Long maxValue) {
return value >= minValue && value <= maxValue;
}
/**
*
*
* @param dateString "yyyy-MM-dd'T'HH:mm:ss.SSS"
* @param timezone UTCAsia/Shanghai
* @return
* @throws Exception
*/
public static long convertToMillisWithTimezone(String dateString, String timezone) {
try {
// 设置日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
// 设置解析时使用的时区
sdf.setTimeZone(TimeZone.getTimeZone(timezone));
// 解析日期字符串为 Date 对象
Date date = sdf.parse(dateString);
// 获取项目默认时区
TimeZone defaultTimeZone = TimeZone.getDefault();
// 使用默认时区的 Calendar 计算
Calendar calendar = Calendar.getInstance(defaultTimeZone);
calendar.setTime(date);
// 返回该时区对应的毫秒时间戳
return calendar.getTimeInMillis();
} catch (Exception e) {
return 0;
}
}
/**
* (UTC)
*
* @param dateStr
* @param pattern ("yyyy-MM-dd HH:mm:ss")
* @return
* @throws ParseException
*/
public static long toTimestamp(String dateStr, String pattern) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.parse(dateStr).getTime();
} catch (Exception e) {
return 0;
}
}
2025-02-11 15:27:15 +08:00
}