javadatetimedate

Removing time from a Date object?


I want to remove time from Date object.

DateFormat df;
String date;
df = new SimpleDateFormat("dd/MM/yyyy");
d = eventList.get(0).getStartDate(); // I'm getting the date using this method
date = df.format(d); // Converting date in "dd/MM/yyyy" format

But when I'm converting this date (which is in String format) it is appending time also.

I don't want time at all. What I want is simply "21/03/2012".


Solution

  • The quick answer is :

    No, you are not allowed to do that. Because that is what Date use for.

    From javadoc of Date :

    The class Date represents a specific instant in time, with millisecond precision.

    However, since this class is simply a data object. It dose not care about how we describe it. When we see a date 2012/01/01 12:05:10.321, we can say it is 2012/01/01, this is what you need. There are many ways to do this.

    Example 1 : by manipulating string

    Input string : 2012/01/20 12:05:10.321

    Desired output string : 2012/01/20

    Since the yyyy/MM/dd are exactly what we need, we can simply manipulate the string to get the result.

    String input = "2012/01/20 12:05:10.321";
    String output = input.substring(0, 10);  // Output : 2012/01/20
    

    Example 2 : by SimpleDateFormat

    Input string : 2012/01/20 12:05:10.321

    Desired output string : 01/20/2012

    In this case we want a different format.

    String input = "2012/01/20 12:05:10.321";
    DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
    Date date = inputFormatter.parse(input);
    
    DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
    String output = outputFormatter.format(date); // Output : 01/20/2012
    

    For usage of SimpleDateFormat, check SimpleDateFormat JavaDoc.