public class DateUtils{
private static String pattern = "yyyy-MM-dd HH:mm:ss";
private static String splitRegex = ",";
/**
*
*获取指定日期中的最小时间(LocalDateTime) 时间戳(s)
*
*/
private static long minDateTimeOfDayOfMonth(int year, int month, int day){
LocalDateTime minLocalDateTime = LocalDateTime.now().with(LocalDateTime.MIN).withYear(year).withMonth(month).withDayOfMonth(day);
return LocalDateTime.from(minLocalDateTime).atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
/**
*
*获取时间戳对应日期的最小时间戳 00:00:00
*
*/
public static long minDateTimeOfTimestamp(Long timestamp){
Instant instant = Instant.ofEpochSecond(timestamp);
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
return minDateTimeOfDayOfMonth(localDateTime.getYear(), localDateTime.getMonthValue(), localDateTime.getDayOfMonth());
}
/**
*
*获取指定日期中的最大时间(LocalDateTime)时间戳(s)
*
*/
private static long maxDateTimeOfDayOfMonth(int year, int month, int day){
LocalDateTime maxLocalDateTime = LocalDateTime.now().with(LocalDateTime.MAX).withYear(year).withMonth(month).withDayOfMonth(day);
return LocalDateTime.from(maxLocalDateTime).atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
/**
*
*获取时间戳对应的日期的最大时间戳 23:59:59
*
*/
public static long maxDateTimeOfTimestamp(Long timestamp){
Instant instant = Instant.ofEpochSecond(timestamp);
LocalDateTime localDateTime = localDateTime.ofInstant(instant, ZoneId.systemDefault());
return maxDateTimeOfDayOfMonth(localDateTime.getYear(), localDateTime.getMonthValue(), localDateTime.getDayOfMonth());
}
/**
*
*获取指定时间格式的时间戳
* @param time 格式 (20190101)
* @return 时间戳
*/
public static Long getAppointDate(String time){
StringBuilder stringBuilder = new StringBuilder(time);
stringBuilder.insert(6,"-");
stringBuilder.insert(4,"-");
DateTimeFormatter ftf = DateTimeFormatter.ofPattern(pattern);
LocalDateTime parse = LocalDateTime.parse(stringBuilder.append(" 00:00:00").toString(),ftf);
return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
/**
*
* 时间戳返回字符串
* @param time long类型的time(单位:秒)
* @return 格式化后的字符串(2019-01-01 00:00:00)
*/
public static String getFormatDate(Long time){
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(time);
}
/**
*
* 获取今天23:59:59的时间戳(单位:s)
*
*/
public static long getTodayLastTimestamp(){return maxDateTimeOfTimestamp(getNewTime());}
/**
*
* 获取今天00:00:00的时间戳(单位:s)
*
*/
public static long getTodayFirstTimestamp(){return minDateTimeOfTimestamp(getNewTime());}
/**
*
* 获取当前时间戳(单位:s)
*
*/
public static Long getNewTime(){return System.currentTimeMillis() / 1000;}
/**
*
* 分割带逗号的字符串,得到list集合
*
*/
public static List<String> splitStrAsList(String str){
if(StringUtils.isEmpty(str)){
return new ArrayList();
}
String[] strArr = str.split(splitRegex);
return Arrays.asList(strArr);
}
}
/**
* 获取当月所有天
*
* @param timeStamp 时间戳(秒)
* @return 月份时间集合 例如:2020-09-01、2020-09-02......
*/
public static List<String> getDayListOfMonth(Long timeStamp) {
List<String> list = new ArrayList<>();
Calendar calendar = Calendar.getInstance(Locale.CHINA);
//转为毫秒
calendar.setTimeInMillis(timeStamp * 1000);
int year = calendar.get(Calendar.YEAR);
//使用日历类,月份需加1
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.getActualMaximum(Calendar.DATE);
for (int i = 1; i <= day; i++) {
//月补零、天补零
String date = year + "-" + (month < 10 ? "0" + month : month)
+ "-" + (i < 10 ? "0" + i : i);
list.add(date);
}
return list;
}
/**
* 将每月的每天填充值,没有数据的填上默认值,灵活修改其中的model类作为模板使用
*/
private List<TrendAnalysisVO> fillList(Long time, List<TrendAnalysisVO> list) {
List<String> dateList = MyDateUtils.getDayListOfMonth(time);
List<TrendAnalysisVO> resultList = dateList.stream()
.map(m -> new TrendAnalysisVO(m, DEFAULT_VALUE))
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(list)) {
return resultList;
}
list.forEach(item -> resultList.removeIf(i -> i.getDate().equals(item.getDate())));
resultList.addAll(list);
resultList.sort(Comparator.comparing(TrendAnalysisVO::getDate));
return resultList;
}
/**
* zip解压
*
* @param srcFile 源zip文件
* @param destDirPath 解压目录
* @return 解压结果
*/
public static boolean unzip(File srcFile, String destDirPath) {
final int BUFFER_SIZE = 1024;
try (ZipFile zipFile = new ZipFile(srcFile)) {
Enumeration<?> enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
File file = new File(destDirPath + File.separator + zipEntry.getName());
if (zipEntry.isDirectory()) {
if (!file.mkdirs()) {
log.warn("解压时创建文件夹失败!");
}
} else {
if (!file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
log.warn("解压时创建文件夹失败!");
continue;
}
}
if (!file.createNewFile()) {
log.warn("解压时创建文件失败!file->{}", file.getName());
continue;
}
try (InputStream is = zipFile.getInputStream(zipEntry);
FileOutputStream fos = new FileOutputStream(file)) {
int len;
byte[] buf = new byte[BUFFER_SIZE];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
} catch (IOException e) {
log.warn("解压文件时发生了异常!", e);
}
}
}
} catch (Exception e) {
log.error("文件解压失败!path->{}", srcFile.getPath(), e);
return false;
}
return true;
}
/**
* 执行Linux命令获取结果,命令集必须存在值,否则返回空字符串
*
* @param spStr 结果按行分割符 可为空,为空时不做拼接
* @param cmdStr 命令集
* @return 命令执行结果
*/
public static String execLinuxOrder(String spStr, String... cmdStr) {
StringBuilder result = new StringBuilder();
Process process = null;
if (cmdStr != null && cmdStr.length > 0) {
try {
//数组和非数组分支不一致,一个值默认是非数组
if (cmdStr.length == 1) {
process = Runtime.getRuntime().exec(cmdStr[0]);
} else {
process = Runtime.getRuntime().exec(cmdStr);
}
} catch (IOException e) {
log.error("执行Linux命令出错!", e);
}
} else {
return "";
}
if (process == null) {
return "";
}
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), UTF_8))) {
String tempStr;
while ((tempStr = bufferedReader.readLine()) != null) {
result.append(tempStr);
if (StringUtils.hasLength(spStr)) {
result.append(spStr);
}
}
closeProcess(process);
} catch (IOException e) {
log.error("执行Linux命令获取输出流出错!", e);
}
return result.toString();
}
/**
* object转list
*
* @param obj object
* @param clazz 需要转成的类型
* @return java.util.List<T>
*/
public static <T> List<T> castList(Object obj, Class<T> clazz) {
List<T> result = new ArrayList<>();
if (obj instanceof List<?>) {
for (Object o : (List<?>) obj) {
result.add(clazz.cast(o));
}
return result;
}
return null;
}