开发中经常会用到生成失效时间,比如会员开通或者订单失效时间,可根据需求使用相应的方法。
方法中还附带着推算当前时间前X分钟的代码。可以根据顺推算的方法,逆推得到。
static GregorianCalendar GC = new GregorianCalendar();
private static final SimpleDateFormat SF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 小时推算
*
* @param i 小时
* @param d 初始时间
* @return
*/
public static String getXS(int i, Date d) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.HOUR,
calendar.get(Calendar.HOUR) + i);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}
/**
* 分钟推算
*
* @param i 分钟
* @param d 初始时间
* @return
*/
public static String getFz(int i, Date d) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.MINUTE,
calendar.get(Calendar.MINUTE) + i);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}
/**
* 分钟逆推
* @param i 分钟
* @param d 初始时间
* @return
*/
public static String getFzNitui(int i, Date d) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.MINUTE,
calendar.get(Calendar.MINUTE) - i);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}
/**
* 天数推算
*
* @param i 天数
* @param d 初始时间
* @return
*/
public static String getDay(int i, Date d) {
GC.setTime(d);
GC.add(5, +i);
GC.set(GC.get(Calendar.YEAR), GC.get(Calendar.MONTH), GC.get(Calendar.DATE));
synchronized (SF) {
return SF.format(GC.getTime());
}
}
/**
* 天数逆推
*
* @param i 天数
* @param d 初始时间
* @return
*/
public static String getDayNi(int i, Date d) {
GC.setTime(d);
GC.add(5, -i);
GC.set(GC.get(Calendar.YEAR), GC.get(Calendar.MONTH), GC.get(Calendar.DATE));
synchronized (SF) {
return SF.format(GC.getTime());
}
}
/**
* 周数推算
*
* @param i 周数
* @param d 初始时间
* @return
*/
public static String getWeek(int i, Date d) {
GC.setTime(d);
GC.add(3, +i);
GC.set(GC.get(Calendar.YEAR), GC.get(Calendar.MONTH), GC.get(Calendar.DATE));
synchronized (SF) {
return SF.format(GC.getTime());
}
}
/**
* 月数推算
*
* @param i 月数
* @param d 初始时间
* @return
*/
public static String getMonth(int i, Date d) {
GC.setTime(d);
GC.add(2, +i);
GC.set(GC.get(Calendar.YEAR), GC.get(Calendar.MONTH), GC.get(Calendar.DATE));
synchronized (SF) {
return SF.format(GC.getTime());
}
}
/**
* 月数逆推
*
* @return
*/
public static String getMonthNi(int i, Date d) {
GC.setTime(d);
GC.add(2, -i);
GC.set(GC.get(Calendar.YEAR), GC.get(Calendar.MONTH), GC.get(Calendar.DATE));
synchronized (SF) {
return SF.format(GC.getTime());
}
}