java验证接口时间戳是否过期

阳光穿透心脏的1/2处 2024-04-08 09:41 125阅读 0赞

代码

  1. //计算日期差,不超过5分钟
  2. long diff = Math.abs(CommonDateUtil.diff(new Date(), time, CommonDateUtil.MINUTE_MS));
  3. if (diff < 0 || diff > 5) {
  4. return "已过期,请更新时间戳";
  5. }

工具

  1. package org.springblade.modules.api.utils;
  2. import org.springblade.core.tool.utils.DateUtil;
  3. import org.springblade.core.tool.utils.Func;
  4. import java.io.UnsupportedEncodingException;
  5. import java.lang.reflect.Field;
  6. import java.lang.reflect.InvocationTargetException;
  7. import java.lang.reflect.Method;
  8. import java.math.BigDecimal;
  9. import java.net.URLDecoder;
  10. import java.text.DecimalFormat;
  11. import java.text.NumberFormat;
  12. import java.text.ParseException;
  13. import java.text.SimpleDateFormat;
  14. import java.time.Instant;
  15. import java.time.LocalDateTime;
  16. import java.time.ZoneId;
  17. import java.util.*;
  18. import java.util.stream.Collectors;
  19. /**
  20. * 通用工具类
  21. *
  22. * @author Chill
  23. */
  24. public class CommonDateUtil {
  25. private final static String FIRST="1";
  26. private final static String SECOND="2";
  27. private final static String THIRD="3";
  28. private final static String FOUR="4";
  29. /** 毫秒 */
  30. private final static long MS = 1;
  31. /** 每秒钟的毫秒数 */
  32. private final static long SECOND_MS = MS * 1000;
  33. /** 每分钟的毫秒数 */
  34. public final static long MINUTE_MS = SECOND_MS * 60;
  35. /**
  36. * 不够位数的在前面补0,保留num的长度位数字
  37. *
  38. * @param code 码
  39. * @return 编号
  40. */
  41. public static String autoGenericCode(String code, int num) {
  42. String result = "";
  43. result = String.format("%0" + num + "d", Integer.parseInt(code));
  44. return result;
  45. }
  46. /**
  47. * 获取季度
  48. * @param date 当前日期
  49. * @return 季度
  50. * @throws ParseException
  51. */
  52. public static String getQuarter(LocalDateTime date) throws ParseException {
  53. if (Func.isEmpty(date)) {
  54. throw new RuntimeException("日期不能为空");
  55. }
  56. String quarter="";
  57. int month= Func.toInt(DateUtil.format(date,"M"));
  58. if(month>=1&&month<=3){
  59. quarter= date.getYear()+FIRST;
  60. }
  61. if(month>=4&&month<=6){
  62. quarter= date.getYear()+SECOND;
  63. }
  64. if(month>=7&&month<=9){
  65. quarter= date.getYear()+THIRD;
  66. }
  67. if(month>=10&&month<=12){
  68. quarter=date.getYear()+FOUR;
  69. }
  70. return quarter;
  71. }
  72. /**
  73. * 获取百分比
  74. * @param num1
  75. * @param num2
  76. * @return
  77. */
  78. public static String TransPercent(int num1,int num2){
  79. DecimalFormat df =new DecimalFormat();
  80. df.setMaximumFractionDigits(1);
  81. df.setMinimumFractionDigits(1);
  82. if(num2==0){
  83. return "0%";
  84. }else{
  85. String percent = df.format(num1 *100.0 / num2) +"%";
  86. return percent;
  87. }
  88. }
  89. /**
  90. * 字符串转换数字
  91. *
  92. * @param id
  93. * @return
  94. */
  95. public static Integer parseInt(String id) {
  96. Integer uId = 0;
  97. if (id == null || "".equals(id))
  98. return -1;
  99. try {
  100. uId = Integer.parseInt(id);
  101. } catch (NumberFormatException e) {
  102. // e.printStackTrace();
  103. uId = -1;
  104. }
  105. return uId;
  106. }
  107. /**
  108. * 解析前台传来的数据。格式: 1,2,3
  109. *
  110. * @param param
  111. * @return
  112. */
  113. public static Integer[] parseParmas(String param) {
  114. Objects.requireNonNull(param);
  115. Integer[] idList = null;
  116. try {
  117. String id = URLDecoder.decode(param, "utf-8");
  118. Objects.requireNonNull(id);
  119. String[] ids = id.split(",");
  120. int len = ids.length;
  121. idList = new Integer[len];
  122. for (int i = 0; i < len; i++) {
  123. idList[i] = Integer.parseInt(ids[i].trim());
  124. }
  125. } catch (NumberFormatException | UnsupportedEncodingException e) {
  126. e.printStackTrace();
  127. }
  128. return idList;
  129. }
  130. /**
  131. * 非空转换
  132. *
  133. * @param value
  134. * @return
  135. */
  136. public static String noEmpty(Object value) {
  137. return Optional.ofNullable(value)
  138. .map(v -> v.toString())
  139. .orElse("");
  140. }
  141. /**
  142. * 非空转换
  143. *
  144. * @param value
  145. * @return
  146. */
  147. public static Integer noEmpty(Integer value) {
  148. return value == null ? 0 : value;
  149. }
  150. /**
  151. * LocalDateTime 转换为 Date
  152. *
  153. * @param localDateTime
  154. * @return
  155. */
  156. public static Date LocalDateTimeToDate(LocalDateTime localDateTime) {
  157. ZoneId zone = ZoneId.systemDefault();
  158. Instant instant = localDateTime.atZone(zone).toInstant();
  159. return Date.from(instant);
  160. }
  161. /**
  162. * Date 转换为 LocalDateTime
  163. *
  164. * @param date
  165. * @return
  166. */
  167. public static LocalDateTime DateToLocalDateTime(Date date) {
  168. Instant instant = date.toInstant();
  169. ZoneId zone = ZoneId.systemDefault();
  170. return LocalDateTime.ofInstant(instant, zone);
  171. }
  172. /**
  173. *
  174. * @param dateTime
  175. * @return
  176. */
  177. public static String parseDateStr(LocalDateTime dateTime) {
  178. Objects.requireNonNull(dateTime);
  179. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  180. Date date = LocalDateTimeToDate(dateTime);
  181. return sdf.format(date);
  182. }
  183. /**
  184. * 解析字符串格式的时间
  185. * @param date
  186. * @return
  187. */
  188. public static Map<String, Object> parseDateStr(String date) {
  189. Objects.requireNonNull(date);
  190. Map<String, Object> dateMap = new HashMap<>();
  191. String[] values = date.split(",");
  192. if (values != null && values.length == 2) {
  193. String begin = values[0].trim();
  194. if (begin != null && begin.length() >= 10)
  195. begin = begin.substring(0, 10);
  196. dateMap.put("begin", begin);
  197. String end = values[1].trim();
  198. if (end != null && end.length() >= 10)
  199. end = end.substring(0, 10);
  200. dateMap.put("end", end);
  201. }
  202. return dateMap;
  203. }
  204. /**
  205. * 解析逗号分隔的日期
  206. *
  207. * @param date
  208. * @param isDate
  209. * @return
  210. */
  211. public static Map<String, Object> parseDate(String date, boolean isDate) {
  212. Map<String, Object> dateMap = new HashMap<>();
  213. if(date != null) {
  214. String[] values = date.split(",");
  215. if (values != null && values.length == 2) {
  216. String begin = values[0].trim();
  217. String end = values[1].trim();
  218. if (isDate) {
  219. try {
  220. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  221. Date beginDate = sdf.parse(values[0]);
  222. Date endDate = sdf.parse(values[1]);
  223. //结束日期加一天
  224. Calendar calendar = Calendar.getInstance();
  225. calendar.setTime(endDate);
  226. calendar.add(Calendar.DATE, 1);
  227. endDate = calendar.getTime();
  228. dateMap.put("begin", DateToLocalDateTime(beginDate));
  229. dateMap.put("end", DateToLocalDateTime(endDate));
  230. } catch (ParseException e) {
  231. e.printStackTrace();
  232. }
  233. } else {
  234. dateMap.put("begin", begin);
  235. dateMap.put("end", end);
  236. }
  237. }
  238. }
  239. return dateMap;
  240. }
  241. /**
  242. * 获取对象的所有属性
  243. *
  244. * @param obj
  245. * @return
  246. */
  247. public static Field[] getFields(Object obj) {
  248. return getFields(obj, false);
  249. }
  250. /**
  251. * 获取对象的所有属性,包括从父类继承的属性
  252. *
  253. * @param obj
  254. * @param parent
  255. * @return
  256. */
  257. public static Field[] getFields(Object obj, boolean parent) {
  258. Objects.requireNonNull(obj);
  259. List<Field> fieldList = new ArrayList<>();
  260. Class<? extends Object> clazz = obj.getClass();
  261. while (clazz != null) {
  262. fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
  263. clazz = parent ? clazz.getSuperclass() : null;
  264. }
  265. Field[] fields = new Field[fieldList.size()];
  266. return fieldList.toArray(fields);
  267. }
  268. /**
  269. * 获取通用对象字段的值
  270. *
  271. * @param object
  272. * @param fieldName
  273. * @return
  274. * @throws NoSuchMethodException
  275. * @throws IllegalAccessException
  276. * @throws InvocationTargetException
  277. */
  278. public static Object getFieldValue(Object object, String fieldName)
  279. throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
  280. Objects.requireNonNull(object);
  281. Object value = null;
  282. String getName = capitalize(fieldName);
  283. if (notEmpty(getName)) {
  284. Method m = object.getClass().getMethod("get" + getName);
  285. value = m.invoke(object);
  286. }
  287. return value;
  288. }
  289. /**
  290. * 验证字符串是否为空
  291. *
  292. * @param value
  293. * @return
  294. */
  295. public static boolean notEmpty(String value) {
  296. return value != null && !"".equals(value);
  297. }
  298. /**
  299. * 首字母转换为大写
  300. *
  301. * @param fieldName
  302. * @return
  303. */
  304. public static String capitalize(String fieldName) {
  305. String getName = "";
  306. if (notEmpty(fieldName)) {
  307. getName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
  308. }
  309. return getName;
  310. }
  311. /**
  312. * 从字符串开始处抽取指定长度的字符
  313. *
  314. * @param content
  315. * @param len
  316. * @return
  317. */
  318. public static String extract(String content, int len) {
  319. return Optional.ofNullable(content)
  320. .filter(c -> c.length() > len)
  321. .map(c -> {
  322. StringBuffer buffer = new StringBuffer();
  323. buffer.append(c.substring(0, len)).append("...");
  324. return buffer.toString();
  325. }).orElse(content);
  326. }
  327. /**
  328. * 字符串数据转为数字数组
  329. * @param str
  330. * @return
  331. */
  332. public static Integer[] str2IntArray(String str) {
  333. String[] strs = str.split(",");
  334. Integer[] original = new Integer[strs.length];
  335. for (int i = 0, len = strs.length; i < len; i++) {
  336. original[i] = parseInt(strs[i]);
  337. }
  338. return original;
  339. }
  340. /**
  341. * 计算占比
  342. * @param num
  343. * @param total
  344. * @return
  345. */
  346. public static Float calcPercent(int num, int total) {
  347. Float rate = (num * 10000.0f) / total;
  348. return ((new BigDecimal(rate).setScale(0, BigDecimal.ROUND_HALF_UP)).floatValue()) / 10000;
  349. }
  350. /**
  351. * Check list not null
  352. * @param list
  353. * @return
  354. */
  355. public static boolean validList(List<?> list) {
  356. if (list != null && list.size() > 0) {
  357. return true;
  358. }
  359. return false;
  360. }
  361. public static String deleteAllHTMLTag(String source) {
  362. if (source == null) {
  363. return "";
  364. }
  365. String s = source;
  366. /** 删除普通标签 */
  367. s = s.replaceAll("<(S*?)[^>]*>.*?|<.*? />", "");
  368. /** 删除转义字符 */
  369. s = s.replaceAll("&.{2,6}?;", "");
  370. return s;
  371. }
  372. public static Map<String, Map<String, Object>> mapAscSortedByKey(Map<String, Map<String, Object>> unsortMap) {
  373. Map<String, Map<String, Object>> result = new HashMap<>();
  374. if (unsortMap != null) {
  375. unsortMap.entrySet().stream().sorted(Map.Entry.<String, Map<String, Object>>comparingByKey())
  376. .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
  377. }
  378. return result;
  379. }
  380. public static Date strToDate(String dateStr) {
  381. return strToDate(dateStr, "yyyy-MM-dd");
  382. }
  383. public static Date strToDate(String dateStr, String format) {
  384. Date date = new Date();
  385. if (dateStr != null) {
  386. try {
  387. SimpleDateFormat sdf = new SimpleDateFormat(format);
  388. date = sdf.parse(dateStr);
  389. } catch (ParseException e) {
  390. date = new Date();
  391. }
  392. }
  393. return date;
  394. }
  395. /**
  396. *
  397. * @param date
  398. * @return
  399. */
  400. public static String parseDateStr(Date date) {
  401. return parseDateStr(date, "yyyy-MM-dd");
  402. }
  403. public static String parseDateStr(Date date, String format) {
  404. String dateStr = "";
  405. if (date != null) {
  406. SimpleDateFormat sdf = new SimpleDateFormat(format);
  407. dateStr = sdf.format(date);
  408. }
  409. return dateStr;
  410. }
  411. public static double calcRate(long num, long total) {
  412. double rate = 0;
  413. if (num != 0) {
  414. try {
  415. double temp = (float) (num * 100) / total;
  416. BigDecimal b = new BigDecimal(temp);
  417. rate = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
  418. } catch (Exception e) {
  419. }
  420. }
  421. return rate;
  422. }
  423. public static String calcPerc(long num, long total) {
  424. String result = "0";
  425. if (total != 0) {
  426. if (num > total) {
  427. num = total;
  428. }
  429. try {
  430. // 创建一个数值格式化对象
  431. NumberFormat numberFormat = NumberFormat.getInstance();
  432. // 设置精确到小数点后2位
  433. numberFormat.setMaximumFractionDigits(2);
  434. result = numberFormat.format((float) num / (float) total * 100);
  435. } catch (Exception e) {
  436. }
  437. }
  438. return result + "%";
  439. }
  440. public static int objToInt(Object obj){
  441. if(obj==null){
  442. return 0;
  443. }
  444. if(obj instanceof Double){
  445. return ((Double) obj).intValue();
  446. }
  447. if(obj instanceof BigDecimal){
  448. return ((BigDecimal) obj).intValue();
  449. }
  450. return Integer.parseInt(obj.toString());
  451. };
  452. /**
  453. * 等待线程结束
  454. * @param workers
  455. */
  456. public static void joinThread(List<Thread> workers){
  457. //等待线程结束
  458. workers.forEach(e->{
  459. try {
  460. e.join();
  461. }catch (Exception ex){
  462. ex.printStackTrace();
  463. }finally {
  464. e.interrupt();
  465. }
  466. });
  467. }
  468. /**
  469. * 计算日期差
  470. * @param subtrahend
  471. * @param minuend
  472. * @param diffField
  473. * @return
  474. */
  475. public static long diff(Date subtrahend, Date minuend, long diffField) {
  476. long diff = minuend.getTime() - subtrahend.getTime();
  477. return diff / diffField;
  478. }
  479. /**
  480. * 将时间戳变为日期
  481. * @param s
  482. * @return
  483. */
  484. public static Date stampToDate(String s){
  485. String res;
  486. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  487. long lt = new Long(s);
  488. Date date = new Date(lt);
  489. res = simpleDateFormat.format(date);
  490. return DateUtil.parse(res, DateUtil.PATTERN_DATETIME);
  491. }
  492. }

发表评论

表情:
评论列表 (有 0 条评论,125人围观)

还没有评论,来说两句吧...

相关阅读