0

I want to display current date in MM-dd-yy format

Date d1=new Date();

Now I want to change in to the mm-dd-yy pattern

So I formatted it using simple date format

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MM-dd-yyyy);

Pattern Now d1 is in string type but I want it as Date type

javaworld
  • 427
  • 1
  • 9
  • 19
  • 2
    Huh? You've defined `d1` as a `Date`, so it's a `Date`, not a `String`. – Oliver Charlesworth Feb 14 '15 at 19:03
  • Well, don't use the same variable then. Even though I cannot imagine, how you squashed `String` into `Date`. Can you please post the whole fragment in question, so that we could understand, what on earth are you doing? – David Jashi Feb 14 '15 at 19:04
  • 1
    You misunderstand the concept of these types. A Date holds a "point in time" without any properties related to how it is written. A String is just that: a sequence of characters that may hold the German or English or American of French or ... representation of such a point in time. – laune Feb 14 '15 at 19:05

1 Answers1

2

This is the difference between model and view.

The model here is the Date object (Date date = new Date();) It contains information about what month, day, and year, hour of day, etc. that the date was created with. It doesn't know anything about formatting.

The view is the string generated by the DateFormat object. You can pass the model (the date object) in to the formatter in order to generate multiple views of the model depending on what fields you're interested in, and how you want them presented.

So the date continues to hold the same date fields regardless of what strings the formatter generates for it. The date and the formatted strings are separate objects. Although we say "format a date", the formatting doesn't actually change the date object in any way.

Your format string is incorrect, to get the month you want "MM-dd-yyyy", "mm" means minutes. See the API documentation for SimpleDateFormat to see what the different pattern letters mean.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276