-2

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.

4

1 回答 1

0

DateFormat#parse()方法只是将字符串转换为日期。它不会更改转换后的 Date 中的任何内容,这意味着它不会存储构造它的格式。

每当您再次打印 Date 对象时,它都会以toString()您得到的默认实现打印。

您需要以特定格式再次打印,然后使用DateFormat#format()方法。


格式应该是yyyy-MM-dd而不是YYYY-MM-dd.

示例代码:

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);

输出:

Sat Jun 07 00:00:00 IST 2014
2014-06-07
于 2014-06-07T18:06:37.613 回答