com.github.javaclub.toolbox.utils.DateTimeUtils Maven / Gradle / Ivy
/*
* @(#)DateTimeUtils.java 2022-12-14
*
* Copyright (c) 2022. All Rights Reserved.
*
*/
package com.github.javaclub.toolbox.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.javaclub.toolbox.ToolBox.Numbers;
import com.github.javaclub.toolbox.ToolBox.Strings;
/**
* DateTimeUtils
*
* @author Gerald Chen
* @version $Id: DateTimeUtils.java 2022-12-14 15:47:55 Exp $
*/
public class DateTimeUtils {
private static final Logger log = LoggerFactory.getLogger(DateTimeUtils.class);
static final int DATE_FORMAT_STR_LENGTH = 10; // (yyyy-MM-dd) 10
static final int TIMESTAMP_STR_LENGTH = 19; // (yyyy-MM-dd HH:mm:ss) 19
static final int MSEL_FORMAT_STR_LENGTH = 23; // (yyyy-MM-dd HH:mm:ss,SSS) 23
static final int NUMERIC_TIMESTAMP_STR_LENGTH = 14; // (yyyyMMddHHmmss) 14
/**
* parse string of format to java.util.Date.
*
* 'yyyy-MM-dd'、'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd HH:mm:ss,SSS' is supported.
*
* @param input the input string.
* @return a java.util.Date
*/
public static java.util.Date toDate(String input) {
if (Strings.isBlank(input)) {
return null;
}
String dealStr = Strings.cleanQuotes(input);
int length = dealStr.length();
SimpleDateFormat sdf = null;
if(4 < length &&length < DATE_FORMAT_STR_LENGTH && dealStr.charAt(4) == '-') {
String[] array = Strings.split(dealStr, "-");
if(null == array || 3 != array.length) {
return null;
}
if(!Numbers.areNumeric(array)) {
return null;
}
StringBuffer sbf = new StringBuffer(array[0]).append("-");
sbf.append(array[1].length()==1 ? ("0" + array[1]) : array[1]).append("-");
sbf.append(array[2].length()==1 ? ("0" + array[2]) : array[2]);
sdf = new SimpleDateFormat("yyyy-MM-dd");
dealStr = sbf.toString();
} else if (length == DATE_FORMAT_STR_LENGTH && dealStr.charAt(4) == '-' && dealStr.charAt(7) == '-') {
sdf = new SimpleDateFormat("yyyy-MM-dd");
} else if (length == TIMESTAMP_STR_LENGTH && dealStr.charAt(4) == '-' && dealStr.charAt(7) == '-'
&& dealStr.charAt(10) == ' ' && dealStr.charAt(13) == ':' && dealStr.charAt(16) == ':') {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} else if (length == MSEL_FORMAT_STR_LENGTH && dealStr.charAt(4) == '-' && dealStr.charAt(7) == '-'
&& dealStr.charAt(10) == ' ' && dealStr.charAt(13) == ':' && dealStr.charAt(16) == ':'
&& (dealStr.charAt(19) == ',' || dealStr.charAt(19) == '.')) {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
if (dealStr.charAt(19) == '.') {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
}
} else if (length == NUMERIC_TIMESTAMP_STR_LENGTH && !dealStr.contains(" ") && !dealStr.contains(":")
&& Strings.isNumeric(dealStr)) {
sdf = new SimpleDateFormat("yyyyMMddHHmmss");
}
if (null == sdf) {
throw new IllegalArgumentException("The format of [" + input + "] is not supported.");
}
try {
return sdf.parse(dealStr);
} catch (ParseException e) {
e.printStackTrace();
System.err.println("Error occured when parsing String [" + input + "] to java.util.Date with the format [" + sdf.toPattern() + "].");
}
return null;
}
/**
* 取当前时间,并自定义:时/分/秒/毫秒
*
* @param hour 时(0~23)
* @param minute 分(0~59)
* @param second 秒(0~59)
* @return 根据当前时间重新定义时/分/秒,并返回
*/
public static Date newDate(int hour, int minute, int second) {
Calendar c = Calendar.getInstance();
c.setTime(new Date());// 设置日历时间
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, second);
// c.set(Calendar.MILLISECOND, millisecond);
return c.getTime();
}
/**
* 判断某个时间是介于时间段表达式中
*
* @param date 时间对象
* @param periodsExpr 格式:1:00:00~5:59:59;20:00:00~23:59:59 或
* 2021-11-11 00:00:00~2021-11-11 23:59:59;2022-11-11 00:00:00~2022-11-11 23:59:59
* @return 是否介于时间段表达式的时间范围内
*/
public static boolean isBetweenTime(Date date, String periodsExpr) {
if (null == date || Strings.isBlank(periodsExpr)) {
return false;
}
String[] pairs = Strings.splitAndTrim(periodsExpr, ";");
for (String pair : pairs) {
if (Strings.isBlank(pair)) {
continue;
}
String[] startAndEnd = Strings.splitAndTrim(pair, "~");
if (null == startAndEnd || 2 != startAndEnd.length) {
continue;
}
boolean between = isBetween(date, startAndEnd);
if (between) {
return true;
}
}
return false;
}
private static boolean isBetween(Date date, String[] startAndEnd) {
Date startTime = null;
Date endTime = null;
try {
int length = startAndEnd[0].length();
if (length >= 5 && length <= 8) {
List startNums = Numbers.asNumberList(Strings.splitAndTrim(startAndEnd[0], ":"));
List endNums = Numbers.asNumberList(Strings.splitAndTrim(startAndEnd[1], ":"));
startTime = newDate(startNums.get(0).intValue(),
startNums.get(1).intValue(),
startNums.get(2).intValue());
endTime = newDate(endNums.get(0).intValue(),
endNums.get(1).intValue(),
endNums.get(2).intValue());
} else {
startTime = toDate(startAndEnd[0]);
endTime = toDate(startAndEnd[1]);
}
if (null != startTime && null != endTime) {
return date.after(startTime) && date.before(endTime);
}
} catch (Exception e) {
log.error("Method isBetween parse date error: {}, timeExpr: {}~{}", e.getMessage(), startAndEnd[0], startAndEnd[1]);
}
return false;
}
}