2013-05-09 76 views
2

我将String转换为Date格式。但它返回"Unparseable date"。例如,字符串日期值转换

String date= "Wednesday, May 15, 2013";

我想将其转换为字符串如"2013-05-15"如何做到这一点?

+1

检查的JavaDoc [SimpleDateFormat的(http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html)。 – Laf 2013-05-09 15:31:21

回答

6

使用SimpleDateFormat两次:第一次解析Date,其他以使其在所需的格式:

Date date; 
String display = new SimpleDateFormat("yyyy-MM-dd").format(
     new SimpleDateFormat("EEEE, MMMM dd, yyyy").parse(date) 
    ); 

你举的例子日期是不幸的,因为它使用的只有3个字母月“五一”,所以我不知道你的月份名是否全部被截断为3个字母,或者它们是全名。我假设有几个月是全名,但如果它们被截断,请在第二个格式字符串中将MMMM更改为MMM

2

像这样的东西可能会帮助(解析日期字符串到日期的对象,并对其进行格式化回到新的格式):

String dateString = "Wednesday, May 15, 2013"; 
    DateFormat format1 = new SimpleDateFormat("EEEE, MMMM dd, yyyy"); 
    Date date = format1.parse(dateString); 

    DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd"); 
    String updatedDateString = format2.format(date); 
    System.out.println("Updated Date > "+updatedDateString); 
0

在我的实验这一点,你需要做类似下面的.. 。请参阅API了解如何构建您的格式字符串。 http://docs.oracle.com/javase/6/docs/api/index.html?java/text/DateFormat.html

String myDateAsString = "Wednesday, May 15, 2013"; 
SimpleDateFormat df = new SimpleDateFormat("EEEE, MMM d, yyyy"); 
Date d = new Date(); 
try { 
    d = df.parse(myDateAsString); 
} catch (ParseException e1) { 
    System.out.println("Could not parse...something wrong...."); 
    e1.printStackTrace(); 
} 
df.applyPattern("yyyy-MM-d"); 
String convertedDate = df.format(d); 
System.out.println(convertedDate); 

这将是一个不错的办法。

+0

想指出这应该有一个微小/更好的性能提供的其他方法,因为你只创建一个Date和一个DateFormat对象。 SimpleDateFormat.applyPattern方法适用于像这样的情况,即采用一种日期格式,然后将其转换为另一种格式。 – 2013-05-09 15:52:36

0

事情是这样的:

import java.text.DateFormat; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class StringDate { 
    public static void main(String[] args) throws ParseException{ 
     String dateString = "Wednesday, May 15, 2013"; 
     DateFormat format1 = new SimpleDateFormat("E, MMM dd, yyyy"); 
     Date date = format1.parse(dateString); 
     DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd"); 
     String updatedDateString = format2.format(date); 
     System.out.println("Updated Date > "+updatedDateString); 
    } 
}