-2

I want to change date format in JAVA as in below. Please help.

-> input is of java.util date datatype (Sat Jan 20 00:00:00 IST 2018)

EX-

Calendar c = Calendar.getInstance();
Date input = c.getTime();
System.out.println(input);//prints[Sat Jan 20 00:00:00 IST 2018]

-> Output should be of java.util date datatype (2018-01-20) EX-

Date output = null;
output = **[logic to convert input to 2018-01-20]**
System.out.print(output);//should print 2018-01-20

I am getting output in String format.

Please help me to find the output in Date format

  • 5
    What have you tried so far? Where is your code? – Mike Tung Feb 03 '18 at 16:10
  • 1
    What do you mean by “DATE” data type? java.util.Date? If so then it has no particular “format”, it’s just a point in time. – algrid Feb 03 '18 at 16:20
  • Yes @algrid input is in java.util format. and i want output also in java.util format. Thankx – Kiran Kumar Feb 03 '18 at 16:39
  • @Pshemo please see the explanations before making if Duplicate question. Thankyou – Kiran Kumar Feb 03 '18 at 16:54
  • @KiranKumar Duplicate contains also answer to your updated question (don't just limit yourself to accepted answer, there are also other ones showing different cases). It contains instructions how to parse string to date type, and then format that date type into other version. Since you already have date you are interested in second step. Take a look at this answer: https://stackoverflow.com/a/4772431 – Pshemo Feb 03 '18 at 16:58
  • The `Date` and `Calendar` classes are long outdated and poorly designed. I recommend you don’t use them. Instead use [the modern `java.time` API](https://docs.oracle.com/javase/tutorial/datetime/). It is so much nicer to work with. – Ole V.V. Feb 05 '18 at 09:36

1 Answers1

0

You will need two SimpleDateFormat objects. One for parsing the input and one for formatting the output.

public static void main(String[] args) throws ParseException {
    String input = "Tue Dec 20 00:00:00 IST 2005";
    SimpleDateFormat inFormat = new SimpleDateFormat("EEE MMM d H:m:s zzz y");
    Date d = inFormat.parse(input);
    System.out.println("d = " + d);
    SimpleDateFormat outFormat = new SimpleDateFormat("y-MM-d");//(2005-12-20
    System.out.println("" + outFormat.format(d));
}

For a more indepth description on how to format the SimpleDateFormat object, check out the Javadocs.

Jose Martinez
  • 11,452
  • 7
  • 53
  • 68