java 时间转换问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 10:18:28
数据库中的字段类型为datatime,现要在java中将时间添加到SQL数据库中。我用
SimpleDateFormat sdf=new SimpleDateFormat("yyy年MM月dd日hh点mm分");
Date date=new Date();
String d=sdf.format(date);
得到的结果是字符串型。求教如何将字符串转换为datatime。

SimpleDateFormat sdf=new SimpleDateFormat("yyy年MM月dd日hh点mm分");
Date date=new Date();
String d=sdf.format(date);
上门是你的代码d是你得到的字符串
Date d2 = sdf.parse(d);
这样就可以转回去了。
就是说sdf.format()从日期到字符串,sdf.parse()从字符串到日期。
而格式的定义方法是一样的。

//没有现成的算法,要自己写个函数转换。

//自己写了一个,应该能满足你的需求
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test{
public static void main(String args[]) {
SimpleDateFormat sdf=new SimpleDateFormat("yyy年MM月dd日hh点mm分");
Date date=new Date();
String dstr=sdf.format(date);
System.out.println(dstr);

//注意,如果这里是你原来的yyy年MM月dd日hh点mm分就会出错
String format="yy年MM月dd日hh点mm分";
Date date2=stringToDate(dstr,format);
System.out.println(date2);

}

public static Date stringToDate(String s, String pformat) {
Date vdate = null;
SimpleDateFormat vsdf = null;
pforma