-3

I am changing my date to String and again from string to date but the date after converting from string to date is different than before .See the Code

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JOptionPane;

public class DateChange {

public static void main(String[] args) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/YYYY");
    Date date = new Date();
    String dateString = dateFormat.format(date);

    Date currentDate = null;
    try {

        currentDate = dateFormat.parse(dateString);

        System.out.println(date + " \n" + currentDate);

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

Here if date object has value Mon Sep 04 12:51:33 IST 2017

Than currentDate has Sun Jan 01 00:00:00 IST 2017

I know something is wrong with the code and I am unable to figure it out.So please point it out for me.

Thanks

Ayush Goyal
  • 415
  • 4
  • 23
  • 1
    What version of Java is that? If Java 8 or more, consider using the new datetime API – fge Sep 04 '17 at 07:26
  • 1
    FYI, you are using troublesome old date-time classes now supplanted by the java.time classes. – Basil Bourque Sep 04 '17 at 07:37
  • Related: [SimpleDateFormat producing wrong date time when parsing “YYYY-MM-dd HH:mm”](https://stackoverflow.com/questions/15916958/simpledateformat-producing-wrong-date-time-when-parsing-yyyy-mm-dd-hhmm) – Ole V.V. Sep 04 '17 at 07:59
  • As an aside, I recommend you scrap the long outdated classes `SimpleDateFormat` and `Date`. Lots of people have experienced lots of problems with them, your is just one in a seemingly neverending row. Today we have so much better in [the modern Java date & time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 04 '17 at 09:29

2 Answers2

2

You're using a wrong format. By checking the documentation you can see that

  • d: day in month
  • M: month in year
  • Y: week year
  • y: year

So the correct format would be: "dd/MM/yyyy"

Alberto S.
  • 7,409
  • 6
  • 27
  • 46
1

Your format String is incorrect. You've used YYYY, but you need yyyy. Like,

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249