-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)

sidgate
  • 14,650
  • 11
  • 68
  • 119
BekaKK
  • 2,173
  • 6
  • 42
  • 80

1 Answers1

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.

Yoda
  • 17,363
  • 67
  • 204
  • 344
  • 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 Mar 28 '18 at 11:22
  • @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. – Yoda Mar 28 '18 at 11:24