虽然开发多年,依然会遇到很多坑,很多知识并不是学以致用,而是实践出真知,譬如:
public static void main(String[] args) {
try {
String dateStr="2019-03-27";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
Date date = sdf.parse(dateStr);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
运行报错,如图:
经过查找原因才知道,SimpleDateFormat只能格式化比自己精度长的时间,或者相同的时间精度,不能格式化比自己精度短的时间。正确的写法如下:
public static void main(String[] args) {
try {
String dateStr="2019-03-27 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
Date date = sdf.parse(dateStr);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
输出如下:
下面是将string转成timestamp的方法,
/**
* string转换成timestamp
*
* @param index
* @return
* @throws Exception
*/
public static Timestamp getTimeStamp(String index) throws Exception
{
if (index == null || index.trim().equals(""))
{
return null;
} else if (index.length() == 10)
{
index += " 00:00:00.000000000";
} else if (index.length() == 19)
{
index += ".000000000";
} else if (index.length() == 26)
{
index = index.substring(0, 10) + " " + index.substring(11, 13) + ":" + index.substring(14, 16) + ":" + index.substring(17, 19)
+ ".000000000";
}
return Timestamp.valueOf(index);
}