SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d = sf.parse("2007-04-16 15:40:40");
to kevinliuu:这是我写的,但我得到的值是null。package com.mypackage; import java.sql.*; import java.text.SimpleDateFormat; public class Test { public static void main(String args[]) { System.out.println(formatDate("2007-2-20 13:59:59")); } public static Date formatDate(String dateStr){ java.sql.Date d=null; try{ SimpleDateFormat sf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); d=(java.sql.Date)sf.parse(dateStr); } catch(Exception e){ return null; } return d; } }
Date d = sf.parse("2007-04-16 15:40:40");
import java.sql.*;
import java.text.SimpleDateFormat;
public class Test
{ public static void main(String args[])
{
System.out.println(formatDate("2007-2-20 13:59:59"));
} public static Date formatDate(String dateStr){
java.sql.Date d=null;
try{
SimpleDateFormat sf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
d=(java.sql.Date)sf.parse(dateStr);
}
catch(Exception e){
return null;
}
return d;
}
}
应该可以的
ParsePosition pos)分析字符串的文本,生成 Date。
此方法试图分析从 pos 给定的索引处开始的文本。如果分析成功,则将 pos 的索引更新为所用最后一个字符后面的索引(不必对直到字符串结尾的所有字符进行分析),并返回分析得到的日期。更新后的 pos 可以用来指示下次调用此方法的起始点。如果发生错误,则不更改 pos 的索引,并将 pos 的错误索引设置为发生错误处的字符索引,并且返回 null。
指定者:
类 DateFormat 中的 parse
参数:
text - 应该分析其中一部分的 String。
pos - 具有以上所述的索引和错误索引信息的 ParsePosition 对象。
返回:
从字符串进行分析的 Date。如果发生错误,则返回 null。
抛出:
NullPointerException - 如果 text 或 pos 为 null。
另请参见:
DateFormat.setLenient(boolean)
return null;
}异常为什么不输出,如果打印一下异常,自己就发现问题所在了.
你用了两个Date,SQL下的,UTIL下的,匹配异常.sf.parse()返回是java.util.Date
这是我写的一段代码:
public boolean UpatePlanList(String cPlanCode,java.sql.Date dStartDate,java.sql.Date dEndDate)
{
boolean Success=false;
String sql="Update BA_PlanList set dStartDate=?,dEndDate=? where cPlanCode=?";
try
{
setConnection();
ps=conn.prepareStatement(sql);
ps.setDate(1,dStartDate);
ps.setDate(2,dEndDate);
ps.setString(3,cPlanCode);
if(ps.executeUpdate()>0){
Success=true;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
freeConnection();
}
catch(Exception e)
{
e.printStackTrace();
}
}
return Success;
}
ps.setDate()的类型是java.sql.Date。
然后用
Date(long date)
Constructs a Date object using the given milliseconds time value.构造一个java.sql.Date对象
package com.mypackage;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;public class MuNiu
{ public static void main(String args[])
{
System.out.println(formatDate("2007-2-20 13:59:59"));
} public static Date formatDate(String dateStr){
java.sql.Date d=null;
try{
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
d=Date(sf.parse(dateStr));
}
catch(Exception e){
return null;
}
return d;
} private static java.sql.Date Date(java.util.Date date) {
java.sql.Date dateTime;
dateTime =new java.sql.Date(date.getTime());
return dateTime;
}}
但得到的值是:2007-02-20
小弟入学java,不知道有没有办法得到2007-2-20 13:59:59