我必须在Date类型中获取Date,而不是在String中。 我有这段代码:
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
如果有人可以提供帮助,谢谢
答案 0 :(得分:2)
Date
对象只代表一个时间点,并且没有格式(或时区)的概念。如果您打印出Date
对象,则首先使用默认格式String
将其转换为EEE MMM dd HH:mm:ss zzz yyyy
。如果您在打印时需要特定格式或以String
表示格式,则需要使用格式化程序,就像您已有的那样。
答案 1 :(得分:0)
换句话说,您希望Date.toString()
返回与DateFormat.format()
相同的内容吗?你可以这样做:
public class MyDate extends Date {
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
public String toString() {
return this.formatter.format(this);
}
}
但你真的想把演示文稿(日期格式)和你的数据混在一起吗?
答案 2 :(得分:0)
这里没有问题,你有一个Date代表,可以像现在一样将它保存到DB中。如果你将它打印到控制台,它会根据默认规则进行格式化,这就是为什么你认为它与你需要的不同,但它实际上已经是正确的价值。
所以,请继续将其放入您的数据库中。
有可能你的数据库会持续获取时间戳,在这种情况下你可以创建一个:
Date d = ...
java.sql.Timestamp ts = new java.sql.Timestamp(d.getTime());
并保存这个。