java将日期转换为字符串,在java中将日期转换为字符串并返回日期

"在程序中,遇到日期转换的问题。将日期从原始格式转换为"dd-MMM-yy"格式后,再使用SimpleDateFormat的parse()方法解析回日期时,日期格式发生了变化。实际上,parse()方法正确地解析了日期,但默认的toString()方法显示了不同的格式。解决方法是使用format()方法来获取格式化的日期字符串,而不是依赖Date对象的属性。"
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值