引入依賴:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.14</version>
</dependency>
工具類代碼:一些常見時間的查詢方法
public class DateUtil {
public static final DateTimeFormatter DATE_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd");
public static final DateTimeFormatter DATE_INT_FORMAT = DateTimeFormat.forPattern("yyyyMMdd");
public static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
public static final DateTimeFormatter INT_MONTH_FORMATTER = DateTimeFormat.forPattern("yyyyMM");
/**
* 解析表達(dá)式為時間戳
*/
public static long parseDate(String date) {
if (StringUtils.isEmpty(date)) {
return 0;
}
return DateTime.parse(date, DATE_FORMAT).toDate().getTime();
}
/**
* 指定日期當(dāng)天開始的時間戳, 單位:ms
*/
public static long getDayBeginMs(long timestamp) {
DateTime date = new DateTime(timestamp);
return date.withMillisOfDay(0).getMillis();
}
/**
* 今天結(jié)束的時間戳, 單位:ms
*/
public static long getTodayEndMs() {
DateTime date = new DateTime();
long nextDayBeginSt = date.withMillisOfDay(0).plusDays(1).getMillis();
return nextDayBeginSt - 1;
}
/**
* 當(dāng)前年開始的時間戳,單位:ms
*/
public static long getYearBeginMs() {
DateTime date = new DateTime();
return date.monthOfYear().withMinimumValue()
.dayOfMonth().withMinimumValue()
.withMillisOfDay(0).getMillis();
}
/**
* 當(dāng)前年結(jié)束的時間戳,單位:ms
*/
public static long getYearEndMs() {
DateTime date = new DateTime();
return date.plusDays(1).dayOfMonth().withMinimumValue()
.dayOfMonth().withMinimumValue()
.withMillisOfDay(0).getMillis();
}
/**
* 前days天開始的時間戳马靠,單位:ms
*/
public static long getDaysBeforeBeginMs(int days) {
DateTime date = new DateTime();
return date.withMillisOfDay(0).plusDays(days).getMillis();
}
/**
* 前days天結(jié)束的時間戳镐确,單位:ms
*/
public static long getDaysBeforeEndMs(int days) {
DateTime date = new DateTime();
return date.minusDays(days).minusDays(1).getMillis() - 1;
}
/**
* 當(dāng)前月開始的時間戳,單位:ms
*/
public static long getMonthBeginMs() {
DateTime date = new DateTime();
return date.dayOfMonth().withMinimumValue()
.withMillisOfDay(0).getMillis();
}
/**
* 當(dāng)前月結(jié)束的事件戳蛇耀,單位:ms
*/
public static long getMonthEndMs() {
DateTime date = new DateTime();
return date.plusMonths(1).dayOfMonth().withMinimumValue()
.withMillisOfDay(0).getMillis();
}
/**
* 指定月份的最后一天
*
* @param month 202201
* @return 20220131
*/
public static int getMonthLastDay(int month) {
DateTime date = DateTime.parse(String.valueOf(month), INT_MONTH_FORMATTER);
return Integer.parseInt(DATE_INT_FORMAT.print(date.dayOfMonth().withMaximumValue().getMillis()));
}
/**
* 獲取前n天的格式化的時間格式:yyyy-MM-dd
*/
public static String getDayFormatBefore(int days) {
DateTime date = new DateTime();
return DATE_FORMAT.print(date.withMillisOfDay(0).minusDays(days).getMillis());
}
}