java的Date类型转换成MySQL的DateTime类型

在网络游戏开发中,常常需要将记录游戏开始的时间和结束的时间,并写到数据库中去。各种数据库的日期类型于java的Date类型往往是不一致的,需要转换。下面我写了一个java的Date类型到MySQL的DateTime类型的转换。

import java.util.Date;

public class DateTest
{
/**
* @param date:java.util.Date
* @return the string of date in MySQL DateTime format like "2005-12-16 16:03:45".
*/
public static String DateToMySQLDateTimeString(Date date)
{
final String[] MONTH = {
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec",
};

StringBuffer ret = new StringBuffer();
String dateToString = date.toString();//like "Sat Dec 17 15:55:16 CST 2005"
ret.append(dateToString.substring(24,24+4));//append yyyy
String sMonth = dateToString.substring(4,4+3);
for(int i=0;i<12;i++) {//append mm
if(sMonth.equalsIgnoreCase(MONTH[i])) {
if((i+1) < 10)
ret.append("-0");
else
ret.append("-");
ret.append((i+1));
break;
}
}

ret.append("-");
ret.append(dateToString.substring(8,8+2));
ret.append(" ");
ret.append(dateToString.substring(11,11+8));

return ret.toString();
}

/**
* @param args
*/
public static void main(String[] args)
{
Date today = new Date();
print(today.toString());
print(DateToMySQLDateTimeString(today));
}

private static void print(String str) {
System.out.println("");
System.out.println(str);
}

}

------------------------------

测试输出:

Sat Dec 17 16:27:07 CST 2005

2005-12-17 16:27:07

你可能感兴趣的:(java的Date类型转换成MySQL的DateTime类型)