I have to get a Date in type Date, not in String. I have this code:
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date1 = new Date();
String开发者_JS百科 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
If anyone could help, thanks
The Date
object just represents a point in time and has no notion of a format (or time zone). If you print out a Date
object it first converts it to a String
using the default formatting of EEE MMM dd HH:mm:ss zzz yyyy
. If you want a specific formatting when you print it or otherwise represent it as a String
, you'll need to use a formatter just like you already have.
In other words, you want Date.toString()
to return the same as DateFormat.format()
? You could just do exactly that:
public class MyDate extends Date {
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
public String toString() {
return this.formatter.format(this);
}
}
But do you really want to mix up presentation (date format) with your data?
There is no problem here, you have a Date representing and can save it into the DB as it is now. If you print it to the console it gets formatted according the default rules, this is why you think it is different from what you need, but it has actually already the right value.
So just go ahead and put it into your DB.
Chances are that you DB will hold on getting a Timestamp, in this case you can create one:
Date d = ...
java.sql.Timestamp ts = new java.sql.Timestamp(d.getTime());
and save this one.
精彩评论