问题描述
|
我必须获得日期类型的日期,而不是字符串的日期。
我有以下代码:
DateFormat formatter = new SimpleDateFormat(\"MM/dd/yy\");
Date date1 = new Date();
String date = (formatter.format(date1));
// At this point I get the date in correct format i.e 05/24/11
Date todaysDate = (Date)formatter.parse(date);
// But after this I get the date in format : Tue May 24 00:00:00 EDT 2011
// whereas I Want to get the date like above i.e 05/24/11
// And in type Date,not in type String
如果有人可以帮忙,谢谢
解决方法
换句话说,您希望
Date.toString()
返回与DateFormat.format()
相同的值吗?您可以完全这样做:
public class MyDate extends Date {
DateFormat formatter = new SimpleDateFormat(\"MM/dd/yy\");
public String toString() {
return this.formatter.format(this);
}
}
但是,您是否真的想将演示文稿(日期格式)与数据混合在一起?
,“ 4”对象仅表示一个时间点,没有格式(或时区)的概念。如果打印出Date
对象,它将首先使用默认格式EEE MMM dd HH:mm:ss zzz yyyy
将其转换为String
。如果要在打印时使用特定格式,或者将其表示为String
,则需要像以前一样使用格式化程序。
,这里没有问题,您有一个Date表示,可以将其保存到现在的数据库中。如果将其打印到控制台,则会根据默认规则对其进行格式化,这就是为什么您认为它与所需内容不同,但实际上它已经具有正确值的原因。
因此,只需将其放入数据库即可。
您的数据库可能会坚持获取时间戳,在这种情况下,您可以创建一个:
Date d = ...
java.sql.Timestamp ts = new java.sql.Timestamp(d.getTime());
并保存这个。