今天用到了日期转换,查了文档写了几个,记录一下以作纪念
日期转换涉及到的包:
1、java.util.TimeZone
2、java.util.Calendar
3、java.util.Date
4、java.sql.Date
5、java.sql.TimeStamp
6、java.sql.Time
7、java.text.DateFormat
8、java.text.SimpleDateFormat
如何获取系统当前日期:
System.currentTimeMillis();
Date date = new Date();
Calendar c = Calendar.getInstance();
日期之间的转换
/**
* String转换为Timestamp
* @param tsStr
* @return Timestamp
*/
public Timestamp stringToTimestamp(String tsStr) {
Timestamp ts = new Timestamp(System.currentTimeMillis());
try {
ts = Timestamp.valueOf(tsStr);
} catch (Exception e) {
e.printStackTrace();
}
return ts;
}
/**
* Timestamp转换为String
* @param ts
* @return String
*/
public String timestampToString(Timestamp ts) {
String tsStr = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
tsStr = sdf.format(ts);
} catch (Exception e) {
e.printStackTrace();
}
return tsStr;
}
/**
* DateTime转换为Date
* @param dateTime
* @return String
*/
public String dateTimetoDate(String dateTime) {
String tsStr = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
tsStr = sdf.format(sdf.parse(dateTime));
} catch (Exception e) {
e.printStackTrace();
}
return tsStr;
}
/**
* 传入日期DateTime,转换为String类型
* @param date
* @return String
*/
public String DatetoStringConvert(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = null;
str = format.format(date);
return str;
}