String to date not working properly [duplicate]

帅比萌擦擦* 提交于 2019-12-13 10:42:38

问题


I am trying from half an hour to convert string to date by using following code:

SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
Date lastCharged = dateFormat.parse(lastChargeDate); 

Every time I run this code the date returned by the system is Sun Dec 29 00:00:00 PKT 2013 Even if i changed the date manually same is the response by the system.

Any help in this regard a lot of work is suspended just because of this blunder.


回答1:


DateFormat#parse() method just convert the String to Date. It doesn't change anything in the converted Date it means it doesn't store the format from which it is constructed.

Whenever you print the Date object again then it prints in its default toString() implementation that's what you are getting.

It you need to print it again in specific format then use DateFormat#format() method.


The format should be yyyy-MM-dd instead of YYYY-MM-dd.

Sample code:

String oldDate="2014-06-07";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date=dateFormat.parse(oldDate);
System.out.println(date);

String newDate=dateFormat.format(date);
System.out.println(newDate);

output:

Sat Jun 07 00:00:00 IST 2014
2014-06-07


来源:https://stackoverflow.com/questions/24100138/string-to-date-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!