-1

I am displaying the date and time in Android with this format: 2015-11-25 23:25:00

How can I change it to the following format? 2015-11-25

I wrote some code ,but not working correctly.

    public static Date toDate(boolean isCurrentDate, String dateString) {
    Date date=null;
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    try {
        if (isCurrentDate)
            date = new Date();
        else
            date = formatter.parse(dateString);
        System.err.println("Printresult" + formatter.parse(formatter.format(date)));

    } catch (ParseException e1) {
        e1.printStackTrace();
    }

    System.err.println("Printresult2" + date.toString());
    return date;
}

I log and result is like this

Wed Nov 25 00:00:00 GMT+00:00 2015

How i can change date format like this : ? (2015-11-25)

4
  • why System.err.println() ?? there is Log.v() or System.out.println() Commented Mar 28, 2018 at 11:19
  • change formatter.parse(formatter.format(date)) to formatter.format(date) :-) Commented Mar 28, 2018 at 11:20
  • I tried it but return data's format is like this Wed Nov 25 00:00:00 GMT+00:00 2015 @Rahul Kumar Commented Mar 28, 2018 at 11:24
  • does the ParseException gets printed? Commented Mar 28, 2018 at 11:27

1 Answer 1

1

You need one format for parsing and another for printing if the formats differ.

The following code deals with displaying the date in the format you want.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(date));

You could alter the beheviour of toString() method by using anonymous class and overrriding toString() method or just create named class deriving from Date, but there is no point to do it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks your attention. My goal is to change date format and return current date with changed format. How I can solved it? I debuged and result was a same @Yoda
@BekaKK You can't set format for a Date object its toString() method will always return the string according to one format, but you can display it according to the format using SimpleDateFormat object and its format() method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.