-8

I am trying to get current Date in the format. "yyyy/MM/dd". I have written following code to achieve this.

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
    Calendar cal = Calendar.getInstance();

        String dateStr = dateFormat.format(cal.getTime());
        currentDate=  dateFormat.parse(dateStr);

The value of current Date after process is this

Mon Jun 20 00:00:00 GMT+05:00 2016,

The value of dateStr after formatting is 2016/06/20

Kindly guide me what i am doing wrong here.

dev90
  • 7,187
  • 15
  • 80
  • 153
  • 3
    Replace the `/` with `-`? – SJuan76 Jun 19 '16 at 21:04
  • 3
    And exchange `dd` and `MM`? – Tunaki Jun 19 '16 at 21:05
  • 2
    `MM` means month, and `20` is not a valid month in any calendar that I'm aware of. Formatting as year-day-month is *very* weird, if that's what you are really trying to do. – Andreas Jun 19 '16 at 21:07
  • Thanks for the comments, but its still returning me `Mon Jun 20 00:00:00 GMT+05:00 2016, ` – dev90 Jun 19 '16 at 21:09
  • That was a typo, i edited that, I need output in `yyyy/MM/dd` format, but its returning me in this `Mon Jun 20 00:00:00 GMT+05:00 2016` – dev90 Jun 19 '16 at 21:10
  • @Kirmani88 There is *no way* for that date format to assign *that* string to `dateStr`. Are you printing `currentDate` instead, because that looks like the default format of `java.util.Date`? Remember, `Date` is a value. It doesn't have a *format*. – Andreas Jun 19 '16 at 21:11
  • I want to compare current date with some other date, that is stored in some database. – dev90 Jun 19 '16 at 21:13
  • Then do that. Why involve date format in that, if the database column is a date datatype? – Andreas Jun 19 '16 at 21:13
  • No its also a string, but its formatted in `yyyy/MM/dd`, so i need to convert that in date and compare it with current date . – dev90 Jun 19 '16 at 21:14
  • Please search Stack Overflow before posting. This has been covered *hundreds* of times already. – Basil Bourque Jun 20 '16 at 05:19

1 Answers1

5

You are confusing how it works.

DateFormat.format takes a Date and converts it to String. It is this string (dateStr in your code) that holds the date in the format you want.

DateFormat.parse takes a String and converts it to Date. The Date object is a date (more precissely a millisecond), it has no format. If you print the resulting Date object, it will be printed using its toString() implementation, which shows the Mon Jun... string. But that value is not related in any way to the DateFormat from which you generated the Date instance.

SJuan76
  • 24,532
  • 6
  • 47
  • 87