diff --git a/IDEA/src/main/java/com/example/api/utils/DataTimeUtil.java b/IDEA/src/main/java/com/example/api/utils/DataTimeUtil.java new file mode 100644 index 00000000..cb54fdba --- /dev/null +++ b/IDEA/src/main/java/com/example/api/utils/DataTimeUtil.java @@ -0,0 +1,52 @@ +package com.example.api.utils; + +import java.text.ParseException; // 导入ParseException类,用于处理解析日期时可能抛出的异常 +import java.text.SimpleDateFormat; // 导入SimpleDateFormat类,用于格式化和解析日期 + +/** + * 数据时间工具类,提供日期时间格式化和解析的方法。 + */ +public final class DataTimeUtil { + + /** + * 获取当前时间的字符串表示。 + * @return 当前时间的字符串,格式为"yyyy-MM-dd HH:mm:ss" + */ + public static String getNowTimeString() { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 创建SimpleDateFormat对象,设置日期时间格式 + return df.format(System.currentTimeMillis()); // 格式化当前系统时间并返回 + } + + /** + * 解析日期时间字符串为时间戳。 + * @param s 日期时间字符串,格式应为"yyyy-MM-dd HH:mm:ss" + * @return 对应的时间戳,如果解析失败返回0 + */ + public static long parseTimeStamp(String s) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 创建SimpleDateFormat对象,设置日期时间格式 + long t = 0; // 初始化时间戳变量 + try { + t = df.parse(s).getTime(); // 解析日期时间字符串并获取时间戳 + } catch (ParseException e) { + e.printStackTrace(); // 如果解析失败,打印异常堆栈 + } + return t; // 返回时间戳 + } + + /** + * 判断给定的日期是否在当前日期之后。 + * @param time 日期字符串,格式应为"yyyy-MM-dd" + * @return 如果给定日期在当前日期之后返回true,否则返回false + */ + public static boolean isAfterNow(String time) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // 创建SimpleDateFormat对象,设置日期格式 + long t = 0; // 初始化时间变量 + try { + t = df.parse(time).getTime(); // 解析日期字符串并获取时间戳 + } catch (ParseException e) { + e.printStackTrace(); // 如果解析失败,打印异常堆栈 + } + return t > System.currentTimeMillis(); // 比较时间戳,判断是否在当前时间之后 + } + +}