-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

4
  • 1
    What version of Java is that? If Java 8 or more, consider using the new datetime API Commented Sep 4, 2017 at 7:26
  • 1
    FYI, you are using troublesome old date-time classes now supplanted by the java.time classes. Commented Sep 4, 2017 at 7:37
  • Related: SimpleDateFormat producing wrong date time when parsing “YYYY-MM-dd HH:mm” Commented Sep 4, 2017 at 7: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. Commented Sep 4, 2017 at 9:29

2 Answers 2

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"

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This silly mistake took my 3 hours.
1

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

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.