在java中将日期转换为字符串并返回日期 [英] converting date to string and back to date in java

查看:150
本文介绍了在java中将日期转换为字符串并返回日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我试图将日期转换为字符串到指定的格式,然后回到最后。我需要日期为dd-MMM-yy格式。所以,我使用SimpleDateFormat将日期转换为dd-MMM-yy格式,如

  SimpleDateFormat sdf = new SimpleDateFormat(dd -MMM-yy); 
String bookingDate = sdf.format(myDate);

结果是我的预期,那是23-May-12,但是当我将字符串转换回来到目前为止
使用parse(),它正在改变为Wed May 23 13:16:14 IST 2012.



有没有办法将字符串转换回到目前为止,不改变格式。我严格需要将指定格式的日期对象传递给查询。



任何帮助都不胜感激。



感谢

解决方案


当我使用parse()将字符串转回日期时,它正在改变到Wed May 23 13:16:14 IST 2012.


这不是真的,它转换回日期正确地,当您尝试打印Date实例时,它调用toString()方法,它具有固定的格式输出,所以如果你想要格式化的日期你需要使用 format() 方法



简而言之,解析方法将 String 解析为日期没有 Date的财产,日期,其格式保持格式,因此您需要使用 format()方法无论如何


In my program iam trying to convert the date to string to specified format and then back to date. I need the date to be in dd-MMM-yy format. So, I am converting the date to dd-MMM-yy format using SimpleDateFormat like,

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
String bookingDate = sdf.format(myDate);

The result is what i expected, that is 23-May-12 but when i convert the string back to date using parse(), it is changing to Wed May 23 13:16:14 IST 2012.

Is there any way to convert the string back to date without changing format. I strictly need to pass the date object in the specified format to the query.

Any help is appreciated.

Thanks

解决方案

when i convert the string back to date using parse(), it is changing to Wed May 23 13:16:14 IST 2012.

That is not true, It converts back to Date correctly, When you try to print Date instance, It invokes toString() method and it has fixed formated output so if you want the formatted date you need to use format() method

In short parse method parses the String to Date there is no property of Date which holds format so you need to use format() method anyhow

这篇关于在java中将日期转换为字符串并返回日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆