工具类DateAndStampUtils:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateAndStampUtils { /** * 时间转时间戳 * * @param time 如:2021-09-29 14:46:37 */ public static String dateToStamp(String time) { String res; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = simpleDateFormat.parse(time); } catch (ParseException e) { e.printStackTrace(); } long ts = date.getTime(); res = String.valueOf(ts); return res; } /** * 时间戳转时间 * * @param stamp 如:1632897997000 */ public static String stampToDate(String stamp) { String res; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long lt = new Long(stamp); Date date = new Date(lt); res = simpleDateFormat.format(date); return res; } /** * 时间增加minute分钟 * * @param time 如:2021-09-29 14:44:37 * @param minute 要增加的分钟数 如:2 */ public static String addTime(String time, int minute) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = format.parse(time); } catch (ParseException e) { e.printStackTrace(); } Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.MINUTE, minute);//增加minute分钟 System.out.println(format.format(c.getTime())); return format.format(c.getTime()); } /** * 计算两个时间戳的差 * * @param oldTime 如:1632897877560 * @param NewTime 如: 1632897997000 */ public static Long timeGap(String oldTime, String NewTime) { Long time1 = Long.valueOf(oldTime); Long time2 = Long.valueOf(NewTime); return time2 - time1; } /** * 计算两个时间的时间戳的差是否超过 minute分钟 * * @param oldTime 如:1632897877560 * @param NewTime 如: 1632897997000 */ public static boolean calculateStamp(String oldTime, String NewTime, int minute) { long gap = timeGap(oldTime, NewTime); long allStamp = minute * 60000; if (gap <= allStamp) { return false; } return true; } }
测试:
public class MainServer { public static void main(String[] args) { //获取当前时间戳 Long nowStamp = System.currentTimeMillis(); System.out.println("当前时间戳是:"+nowStamp); //时间转时间戳 String timeStr = "2021-09-29 14:46:37"; String stamp = DateAndStampUtils.dateToStamp(timeStr); System.out.println("2021-09-29 14:46:37转为时间戳是:"+stamp); //时间戳转换为时间 String stampStr = "1632897997000"; String time = DateAndStampUtils.stampToDate(stampStr); System.out.println("1632897997000转为时间是:"+time); //计算两个时间戳的差是否超过1分钟 //1632897877000代表时间2021-09-29 14:44:37,1632897997000代表时间2021-09-29 14:46:37 boolean whetherExceed = DateAndStampUtils.calculateStamp("1632897877000", "1632897997000", 1); if (whetherExceed) { System.out.println("从1632897877000到1632897997000已经超过了1分钟"); }else { System.out.println("从1632897877000到1632897997000没有超过1分钟"); } } }
输出结果:
当前时间戳是:1632970115657 2021-09-29 14:46:37转为时间戳是:1632897997000 1632897997000转为时间是:2021-09-29 14:46:37 从1632897877000到1632897997000已经超过了1分钟