由于做项目的时候不免会遇到很多时间转换的问题,处理不好会带来不必要的麻烦,下面我将介绍一下本人实际项目开发过程中遇到的关于时间问题的解决方案:
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateConvert {
//----------------Timestamp--------------------------
//获取当前系统时间毫秒数
public Timestamp convert() {
Timestamp ts = new Timestamp(System.currentTimeMillis());
return ts;
}
//字符串转时间,Timestamp类型
public Timestamp StringtoTime(String s)throws Exception{
DateFormat df = DateFormat.getDateInstance();
Date d = df.parse(s);
long da = d.getTime();
Timestamp ts = new Timestamp(da);
return ts;
}
//字符串转时间,Timestamp类型
public Timestamp StringtoTime(String s)throws Exception{
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = df1.format( StringtoDate2(s));
Timestamp ts = Timestamp.valueOf(time);
return ts;
}
//----------------java.sql.date--------------------
//字符串转java.sql.date
public java.sql.Date StringtoDate(String s) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date=sdf.parse(s);
return new java.sql.Date(date.getTime());
}
//字符串转java.sql.date
public java.sql.Date StringtoDate2(String s) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=sdf.parse(s);
return new java.sql.Date(date.getTime());
}
//得到系统sql时间
public java.sql.Date SysDate() throws Exception{
String dt = new String(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date=sdf.parse(dt);
return new java.sql.Date(date.getTime());
}
//-----------------java.util.date-------------------
//字符串转java.util.date
public Date StringtoUtilDate(String s) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date=sdf.parse(s);
return date;
}
//字符串转java.util.date
public Date stToDate(String s){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
//获取一个月以前的时间,并转换成字符串
public String getStringDate() throws Exception{
SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = new Date();
Calendar date = Calendar.getInstance();
date.setTime(beginDate);
date.set(Calendar.DATE, date.get(Calendar.DATE)+30);
Date endDate = dft.parse(dft.format(date.getTime()));
String s = dft.format(endDate);
return s;
}
}
以上纯属个人之见解,不足之处敬请见谅!