问题
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