时间格式转换
String、java.util.Date、java.sql.Timestamp
package cays.pkg;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 时间格式之间的相互转换
* java.util.Date, String, java.sql.Timestamp
* @author Chai yansheng
* @create 2019-08-14 14:46
**/
public class MyTimeUtil {
/**
* String-->java.util.Date
* @param str
* @param format
* @return
* @throws ParseException
*/
public Date stringToUtilDate(String str, String format) throws ParseException {
DateFormat df = new SimpleDateFormat(format);
return df.parse(str);
}
/**
* java.util.Date-->String
* @param date
* @param format
* @return
*/
public String utilDateToString(Date date, String format) {
DateFormat df = new SimpleDateFormat(format);
return df.format(date);
}
/**
* String-->java.sql.Timestamp
* @param str
* @param format
* @return
* @throws ParseException
*/
public Timestamp stringToSqlTimestamp(String str, String format) throws ParseException {
DateFormat df = new SimpleDateFormat(format);
return new Timestamp(df.parse(str).getTime());
}
/**
* java.sql.Timestamp-->String
* @param timestamp
* @param format
* @return
*/
public String timestampToString(Timestamp timestamp, String format) {
DateFormat df = new SimpleDateFormat(format);
return df.format(timestamp);
}
/**
* java.util.Date-->java.sql.Timestamp
* @param date
* @return
*/
public Timestamp utilDateToTimestamp(Date date) {
return new Timestamp(date.getTime());
}
/**
* java.sql.Timestamp-->java.util.Date
* @param timestamp
* @return
*/
public Date timestampToUtilDate(Timestamp timestamp) {
return new Date(timestamp.getTime());
}
public static void main(String[] args) throws ParseException {
MyTimeUtil myTimeUtil = new MyTimeUtil();
String str = "2019-08-14 15:32:43";
System.out.println("str:" + str);
Date date = myTimeUtil.stringToUtilDate(str, "yyyy-MM-dd HH:mm:ss");
System.out.println("yyyy-MM-dd HH:mm:ss date:" + myTimeUtil.utilDateToString(date, "yyyy-MM-dd HH:mm:ss"));
System.out.println("yyyy-MM date:" + myTimeUtil.utilDateToString(date, "yyyy-MM"));
Timestamp timestamp = myTimeUtil.stringToSqlTimestamp(str, "yyyy-MM-dd");
System.out.println("yyyy-MM-dd HH:mm:ss timestamp:" + myTimeUtil.timestampToString(timestamp, "yyyy-MM-dd HH:mm:ss"));
}
}