Question

I am having trouble formatting date in java. I have a shopping class that has item name in string, quantity in int and a date in Date.
In the run class I am trying to run this query.

Date  date = new Date(202020);
SimpleDateFormat  dateformat = new SimpleDateFormat("dd-mm-yy");
String date1 = dateformat.format(date);

Shopping shoplist1 = new Shopping ( "iphone",  2, date);

When I try to create a new shopping entery with the date the date does not format. I don't know why but it gives me Thu Jan 01 01:03:22 GMT 1970.

Was it helpful?

Solution 2

From your comment :

"I tried to add date 1, but it wouldn't allow it. It says string can not be converted to date"

You are passing string to your constructor but looks like it can take java.util.Date object

Shopping shoplist1 = new Shopping ( "iphone",  2, date);

Change your constructor signature to take a String object

OR

Pass the date object and perform the formatting in any other relevant location

OTHER TIPS

You are using wrong Date class constructor:

Date  date = new Date(202020);

Means that you are trying to allocate a Date object and initialize it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

You should use something like this:

Shopping shoplist1 = new Shopping ("iphone",  2, 
        new SimpleDateFormat("dd-MM-yy").parse("20-20-20"));

Read documentation to get more difference between DateFormat#parse(...) and DateFormat#format(...)

change SimpleDateFormat dateformat = new SimpleDateFormat("dd-mm-yy"); to SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy");

if I clearly remember small mm mean minutes not month

Read this post about date formatting

and also as say @zvzdhk, you incorrectly use date constuctor.

  • You create the date instance from a timestamps (milliseconds from 1970). I suppose that is not what you are trying to do.
  • You format the date into a string and pass the date. If you want to use the formatted date, you have to pass the string.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top