无论系统格式如何,如何在java中将String转换为Date

Thi*_*Zaw 7 java string

我试图将日期字符串转换为java中的日期对象,而不管当前的系统日期格式如何.因为我想让我的自定义日期格式存储在数据库中.以下是我的代码,请指教我.

public static String dateToString(String date){
    if(date.equals("")) return "";
    if(date == null || date.length() == 0){
        return "";
    }
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    try {
        Date l_date =  format.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(l_date);
        String year = String.format("%04d", calendar.get(Calendar.YEAR));
        String month = String.format("%02d", calendar.get(Calendar.MONTH));
        String day = String.format("%02d", calendar.get(Calendar.DATE));
        return year + month + day;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    }
}
Run Code Online (Sandbox Code Playgroud)

对于SimpleDateFormat,它只能解析我听到的编码格式.

dateToString("16/04/2015");
Run Code Online (Sandbox Code Playgroud)

它可以转换为上面的代码.但是,当我尝试使用以下格式

dateToString("Thursday, April 16, 2015");
Run Code Online (Sandbox Code Playgroud)

我去Unparseable日期:"2015年4月16日星期四"错误.

Mad*_*mer 4

您正在尝试将字符串转换EEEE, MMMM dd, yyyy为以下格式dd/MM/yyyy

首先使用您String尝试转换的正确格式,然后使用您想要将其转换回来的格式...

SimpleDateFormat from = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
SimpleDateFormat to = new SimpleDateFormat("dd/MM/yyyy");

String value = to.format(from.parse(dateString));
Run Code Online (Sandbox Code Playgroud)

现在您可以使用类似的东西DateUtils.parseDate(String, String[])来提供多种不同的格式,但仍然仅限于您可能知道的格式。

更好的解决方案是将值直接存储Date在数据库中。