MyTimeUtil.java
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MyTimeUtil {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Timestamp stringToTimestamp(String format,String time) throws ParseException{
if(time==null) return null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date date = simpleDateFormat.parse(time);
Timestamp timestamp = new Timestamp(date.getTime());
return timestamp;
}
/**
* 得到当前时间
* 返回 2016-02-19 14:37:23格式的时间
* */
public static String getNowTime(){
return simpleDateFormat.format(new Date());
}
/**
* 得到下一个时间
* currentTime 当前时间
* interval 时间间隔(毫秒)
* */
public static Timestamp getNextTime(Timestamp currentTime,int interval){
if(currentTime == null) return null;
int intervalSecond = interval / 1000;
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(currentTime.getTime()));
calendar.add(Calendar.SECOND, intervalSecond);
return new Timestamp(calendar.getTimeInMillis() );
}
/**
* 得到上一个时间
* currentTime 当前时间
* interval 时间间隔(毫秒)
* */
public static Timestamp getPreviousTime(Timestamp currentTime,int interval){
if(currentTime == null) return null;
int intervalSecond = interval / 1000;
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(currentTime.getTime()));
calendar.set(Calendar.SECOND,calendar.get(Calendar.SECOND) - intervalSecond);
return new Timestamp(calendar.getTimeInMillis() );
}
/**
* 得到上一个时间
* currentTime 当前时间
* interval 时间间隔(分钟)
* */
public static Timestamp getPreviousTimeByMinute(Timestamp currentTime,int interval){
if(currentTime == null) return null;
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(currentTime.getTime()));
calendar.set(Calendar.MINUTE,calendar.get(Calendar.MINUTE) - interval);
return new Timestamp(calendar.getTimeInMillis() );
}
/**
* 将timeStamp转为string
* */
public static String timeStampToString(String format,Timestamp timestamp){
if(timestamp == null || format == null) return null;
Date date = new Date(timestamp.getTime());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
String time = null;
try{
time = simpleDateFormat.format(date);
}catch(Exception e){
e.printStackTrace();
}
return time;
}
}