前言:
为了减少重复代码,拿来急用,每次想到时间格式化就很烦恼,各种API以及Date类和LocalDateTime类 ,不熟练的话很混乱,有必要整理成必要的工具类,避免重复造轮子
DateUtil 时间工具类
功能介绍
时间工具类封装了以下常用功能:
- 获取当前时间:获取系统当前的日期和时间。
- 格式化时间:将日期对象或时间戳格式化为指定的时间格式。
- 解析时间:将字符串时间解析为日期对象。
- 获取时间差:计算两个日期之间的时间差,包括天数、小时数、分钟数等。
- 判断时间区间:判断指定时间是否在给定的时间区间内。
- 判断闰年:判断指定年份是否为闰年。
- 获取年份、月份、星期等:从日期对象中提取年份、月份、星期等信息。
主要方法和功能:
getCurrentDate(String pattern)
:获取当前时间的字符串表示。formatToStr(long timestamp, String pattern)
:将时间戳格式化为指定格式的字符串。formatToStr(Date date, String pattern)
:将日期对象格式化为指定格式的字符串。formatStringDate(String dateString, String format)
:将字符串时间按照指定格式进行格式化。getCurrentTime()
:获取当前时间的日期对象。formatTime(Date date, String pattern)
:将日期对象格式化为指定格式的时间字符串。parseTime(String time, String pattern)
:解析指定格式的时间字符串为日期对象。getTimeDifference(Date date1, Date date2, TimeUnit timeUnit)
:计算两个日期之间的时间差。isInTimeRange(Date time, Date startTime, Date endTime)
:判断指定时间是否在给定时间区间内。isLeapYear(int year)
:判断指定年份是否为闰年。getYearFromDate(Date date)
:获取指定日期对象的年份。getMonthFromDate(Date date)
:获取指定日期对象的月份。getWeekdayFromDate(Date date)
:获取指定日期对象的星期。
方便复制粘贴使用
import androidx.core.net.ParseException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* @author: QSY
* @date: 2023/11/30
* 描述: 主要功能格式化时间工具类
*/
public class DateUtil {
// 日期格式年份,例如:2022,2023
public static final String FORMAT_YYYY = "yyyy";
// 其他格式常量...
private static final TimeZone DEFAULT_TIMEZONE = TimeZone.getDefault();
private static TimeZone DefaultTimeZone = TimeZone.getDefault();
/**
* 获取当前时间的字符串表示
*
* @param pattern 时间格式
* @return 当前时间的字符串表示
*/
public static String getCurrentDate(String pattern) {
return formatToStr(new Date(), pattern);
}
/**
* 将时间戳格式化为指定格式的字符串
*
* @param timestamp 时间戳
* @param pattern 时间格式
* @return 格式化后的时间字符串
*/
public static String formatToStr(long timestamp, String pattern) {
return formatToStr(new Date(timestamp), pattern);
}
/**
* 将日期对象格式化为指定格式的字符串
*
* @param date 日期对象
* @param pattern 时间格式
* @return 格式化后的时间字符串
*/
public static String formatToStr(Date date, String pattern) {
DateFormat dateFormat = getDateFormat(pattern);
return dateFormat.format(date);
}
/**
* 获取指定格式的日期格式化对象
*
* @param pattern 时间格式
* @return 日期格式化对象
*/
private static DateFormat getDateFormat(String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
dateFormat.setTimeZone(DEFAULT_TIMEZONE);
return dateFormat;
}
/**
* 格式化字符串时间为指定格式
*
* @param dateString 字符串时间
* @param format 格式
* @return 格式化后的时间字符串
*/
public static String formatStringDate(String dateString, String format) {
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat outputFormat = new SimpleDateFormat(format);
try {
Date date = inputFormat.parse(dateString);
return outputFormat.format(date);
} catch (ParseException | java.text.ParseException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取当前时间的日期对象
*
* @return 当前时间的日期对象
*/
public static Date getCurrentTime() {
return new Date();
}
/**
* 将日期对象格式化为指定格式的时间字符串
*
* @param date 日期对象
* @param pattern 时间格式
* @return 格式化后的时间字符串
*/
public static String formatTime(Date date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
/**
* 解析指定格式的时间字符串为日期对象
*
* @param time 时间字符串
* @param pattern 时间格式
* @return 解析后的日期对象
* @throws ParseException 解析异常
*/
public static Date parseTime(String time, String pattern) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
return sdf.parse(time);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
/**
* 计算两个日期之间的时间差,返回指定时间单位的差值
*
* @param date1 第一个日期对象
* @param date2 第二个日期对象
* @param timeUnit 时间单位
* @return 时间差的差值
*/
public static long getTimeDifference(Date date1, Date date2, TimeUnit timeUnit) {
long difference = date2.getTime() - date1.getTime();
return timeUnit.convert(difference, TimeUnit.MILLISECONDS);
}
/**
* 判断指定时间是否在给定时间区间内
*
* @param time 待判断的时间
* @param startTime 时间区间的开始时间
* @param endTime 时间区间的结束时间
* @return 如果指定时间在时间区间内,返回 true;否则返回 false
*/
public static boolean isInTimeRange(Date time, Date startTime, Date endTime) {
return time.after(startTime) && time.before(endTime);
}
/**
* 判断指定年份是否为闰年
*
* @param year 年份
* @return 如果是闰年,返回 true;否则返回 false
*/
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
/**
* 获取指定日期对象的年份
*
* @param date 日期对象
* @return 年份
*/
public static int getYearFromDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
/**
* 获取指定日期对象的月份
*
* @param date 日期对象
* @return 月份
*/
public static int getMonthFromDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 获取指定日期对象的星期
*
* @param date 日期对象
* @return 星期,1 表示星期一,2 表示星期二,依次类推
*/
public static int getWeekdayFromDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
}
示范案例
// 获取当前时间
Date currentTime = DateUtil.getCurrentTime();
// 格式化时间
String formattedTime = DateUtil.formatTime(currentTime, DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);
// 解析时间
String timeString = "2023-07-14 12:00:00";
Date parsedTime = DateUtil.parseTime(timeString, DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);
// 获取时间差
Date startTime = new Date();
Date endTime = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(2));
long timeDifference = DateUtil.getTimeDifference(startTime, endTime, TimeUnit.MINUTES);
// 判断时间区间
Date time = new Date();
Date startTime = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1));
Date endTime = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1));
boolean isInTimeRange = DateUtil.isInTimeRange(time, startTime, endTime);
// 判断闰年
int year = 2023;
boolean isLeapYear = DateUtil.isLeapYear(year);
// 获取年份、月份、星期
int yearFromDate = DateUtil.getYearFromDate(currentTime);
int monthFromDate = DateUtil.getMonthFromDate(currentTime);
int weekdayFromDate = DateUtil.getWeekdayFromDate(currentTime);
TimeUtil 时间工具类
方法列表
getCurrentWeekOfMonth()
: 获取当前时间为本月的第几周。getCurrentDayOfWeek()
: 获取当前时间为本周的第几天。getCurrentDayOfWeekText()
: 返回当前日期是星期几的文本表示。isTimeInRange(time, startTime, endTime)
: 判断指定时间是否在给定的时间区间内。isTimeInRange(time, startTime, endTime)
: 判断指定时间是否在给定的时间区间内。isInTimeRange(currentTime, startTime, endTime)
: 判断指定时间是否在给定的时间区间内。calculateDaysDifference(startDate, endDate)
: 计算两个日期之间相差的天数。calculateTimeDifference(date)
: 返回友好的时间跨度表示。
方便复制粘贴使用
import java.text.DateFormatSymbols;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
/**
* @author: QSY
* @date: 2023/11/30
* 描述:时间工具处理类
*/
public class TimeUtil {
/**
* 获取当前时间为本月的第几周
*
* @return 本月的第几周
*/
public static int getCurrentWeekOfMonth() {
Calendar calendar = Calendar.getInstance();
int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
return weekOfMonth;
}
/**
* 获取当前时间为本周的第几天
*
* @return 本周的第几天(1代表周一,7代表周日)
*/
public static int getCurrentDayOfWeek() {
LocalDate currentDate = LocalDate.now();
DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
int dayOfWeekValue = dayOfWeek.getValue();
return dayOfWeekValue;
}
/**
* 返回当前日期是星期几
*
* @return 例如:星期日、星期一、星期六等等。
*/
public static String getCurrentDayOfWeekText() {
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
// 获取星期几文本
DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
String[] dayOfWeekTexts = symbols.getWeekdays();
if (dayOfWeek >= Calendar.SUNDAY && dayOfWeek <= Calendar.SATURDAY) {
return dayOfWeekTexts[dayOfWeek];
} else {
return "";
}
}
/**
* 判断指定时间是否在时间区间内
*
* @param time 待判断的时间
* @param startTime 时间区间的开始时间
* @param endTime 时间区间的结束时间
* @return 如果指定时间在时间区间内,返回 true;否则返回 false
*/
public static boolean isTimeInRange(Calendar time, Calendar startTime, Calendar endTime) {
return time.compareTo(startTime) >= 0 && time.compareTo(endTime) <= 0;
}
/**
* 判断指定时间是否在时间区间内
*
* @param time 待判断的时间
* @param startTime 时间区间的开始时间
* @param endTime 时间区间的结束时间
* @return 如果指定时间在时间区间内,返回 true;否则返回 false
*/
public static boolean isTimeInRange(LocalDateTime time, LocalDateTime startTime, LocalDateTime endTime) {
return time.compareTo(startTime) >= 0 && time.compareTo(endTime) <= 0;
}
/**
* 判断指定时间是否在时间区间内
*
* @param currentTime 待判断的时间
* @param startTime 时间区间的开始时间
* @param endTime 时间区间的结束时间
* @return 如果指定时间在时间区间内,返回 true;否则返回 false
*/
public static boolean isInTimeRange(Date currentTime, Date startTime, Date endTime) {
long currentTimeMillis = currentTime.getTime();
return currentTimeMillis >= startTime.getTime() && currentTimeMillis <= endTime.getTime();
}
/**
* 求两个日期相差天数
* @param startDate 开始时间
* @param endDate 结束时间
* @return 相差天数
*/
public static long calculateDaysDifference(Date startDate, Date endDate) {
long differenceMillis = endDate.getTime() - startDate.getTime();
long differenceDays = TimeUnit.MILLISECONDS.toDays(differenceMillis);
return differenceDays;
}
/**
* 返回友好时间跨度
*
* @param date 需要格式化的时间
*
* @return the fit time span
* return 小于1分钟,返回"刚刚"
* return 小于1小时但大于0分钟,返回"X分钟前"
* return 小于1天但大于0小时,返回"X小时前"
* return 昨天,返回"昨天"
* return 大于1天,返回"X天前"
*/
public static String calculateTimeDifference(Date date) {
long currentTime = System.currentTimeMillis();
long timeDifference = currentTime - date.getTime();
// 计算时间差对应的单位
long seconds = timeDifference / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
if (days > 1) {
// 大于1天,返回"X天前"
return days + "天前";
} else if (days == 1) {
// 昨天,返回"昨天"
return "昨天";
} else if (hours > 0) {
// 小于1天但大于0小时,返回"X小时前"
return hours + "小时前";
} else if (minutes > 0) {
// 小于1小时但大于0分钟,返回"X分钟前"
return minutes + "分钟前";
} else {
// 小于1分钟,返回"刚刚"
return "刚刚";
}
}
}
示范案例
// 获取当前时间为本月的第几周
int weekOfMonth = TimeUtil.getCurrentWeekOfMonth();
// 获取当前时间为本周的第几天
int dayOfWeek = TimeUtil.getCurrentDayOfWeek();
// 返回当前日期是星期几的文本表示
String dayOfWeekText = TimeUtil.getCurrentDayOfWeekText();
// 判断指定时间是否在时间区间内
boolean isInRange = TimeUtil.isTimeInRange(time, startTime, endTime);
// 计算两个日期之间相差的天数
long daysDifference = TimeUtil.calculateDaysDifference(startDate, endDate);
// 返回友好的时间跨度表示
String timeDifference = TimeUtil.calculateTimeDifference(date);