Search code examples
javaspringparsingdate-format

How to format java Date


I am working on a Spring project and I have to search Documents by date of upload. So when I pass my date as parameter of a method in DAO layer it's received like: Thu Jun 06 00:03:49 WEST 2013. And I want to format that to : 2013-06-06

I have used this code to do that but it returns 06/06/13 and other constants of DateFormat (like DateFormat.MEDIUM, ...) do not return what I am waiting for.

DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT);       
System.out.println(shortDf.format(new Date())); // return 06/06/13 it's short

I have also tried the SimpleDateFormat like that:

public static Date parseDate(String date, String format)throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat(format,Locale.ENGLISH);
return formatter.parse(date);
}

But it is still throwing a parsing Exception:

java.text.ParseException: Unparseable date: "Thu Jun 06 00:23:33 WEST 2013"
at java.text.DateFormat.parse(DateFormat.java:337)
at TestApp.main(TestApp.java:20)

Solution

  • If you want to format a date to your own format like 2013-06-06, SimpleDateFormatter is a common solution. But what went wrong in your code is that you have a wrong return type for a formatted date. Here's the example:

    Date d=new Date();
    String formattedDate=format(d);
    
    System.out.println("This is your date: "+formattedDate);  
    
    public String format(String date){
      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
      return sdf.format(date);
    }  
    

    To format a date into your own format, use sdf.format, not sdf.parse.
    sdf.parse is used to convert String to Date, while sdf.format used to convert Date to String in a specified format.

    sdf.parse returns Date, sdf.format returns String.