-1

Here's what I need to do :

I want to change the date2 into a Date but not String.

 Date date = new Date();
 DateFormat format = new SimpleDateFormat ("yyyy/MM/dd",Locale.ENGLISH);
 String date2 = format.format(date);

It does not allow me to save date2 as a Date. Someone please help me. Thanks

user3900009
  • 113
  • 2
  • 4
  • 12
  • you have to use parse method. and then give it string formatted date. like this `format.parse("2014/12/12");` – Adi Dec 15 '14 at 11:05
  • [This answer](http://stackoverflow.com/questions/25460965/how-to-convert-string-to-date-format-in-android/25461759#25461759) might help you here. – Tom Dec 15 '14 at 11:18
  • 1
    Why was the accepted answer accepted? It has nothing to do with the question. The correct answer is [the one by Jesper](http://stackoverflow.com/a/27482690/642706) explaining that the Question is nonsense due to a lack of understanding the data types. – Basil Bourque Dec 15 '14 at 18:27
  • Well, just because that one helps me and I don't understand the other one. – user3900009 Mar 17 '15 at 13:08

2 Answers2

3

java.util.Date objects do not have a format. They just represent a date value. You cannot "set the format of a Date object" because a Date object can't store this information.

What you are asking ("how do I set the format of a Date object") is not possible, because that's not how Date objects work.

What you should do instead is just work with the Date object and at the point where it needs to be displayed, you convert it to a String in the desired format using a SimpleDateFormat object.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • because I need my parameter requires a date and I need to format the date to save into my database with the selected format. Or should I change the date to a string instead in the entity. – user3900009 Dec 15 '14 at 11:10
  • 1
    @user3900009 This answer is correct. Your database should be using a date-time data type, probably TIMESTAMP WITH TIME ZONE. Your Java code should use date-time data types. No Strings involved until you want to display the date-time values to the user or your logs. Search StackOverflow for *thousands* of examples. Indeed, always search before posting. – Basil Bourque Dec 15 '14 at 18:31
1
import java.text.SimpleDateFormat;
import java.util.Date;

String your_date = "2014-12-15 00:00:00.0";
DateFormat format = new SimpleDateFormat ("yyyy/MM/dd",Locale.ENGLISH);
Date new_date = format.parse(your_date);
System.out.println(new_date);
Riad
  • 3,822
  • 5
  • 28
  • 39