根据所需的日期格式将字符串更改为日期
我必须获取日期类型的日期,而不是字符串。 我有这个代码:
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
如果有人可以帮忙,谢谢
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Date
对象仅表示时间点,没有格式(或时区)的概念。如果打印Date
对象,它首先使用EEE MMM dd HH:mm:ss zzz yyyy
的默认格式将其转换为String
。如果您在打印或以其他方式将其表示为String
时需要特定的格式,则需要使用已有的格式化程序。The
Date
object just represents a point in time and has no notion of a format (or time zone). If you print out aDate
object it first converts it to aString
using the default formatting ofEEE MMM dd HH:mm:ss zzz yyyy
. If you want a specific formatting when you print it or otherwise represent it as aString
, you'll need to use a formatter just like you already have.换句话说,您希望
Date.toString()
返回与DateFormat.format()
相同的结果吗?您完全可以这样做:但是您真的想将演示文稿(日期格式)与数据混合起来吗?
In other words, you want
Date.toString()
to return the same asDateFormat.format()
? You could just do exactly that: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:
and save this one.