0

I have a code that looks like this:

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2013-06-03 00:00:00");
        System.out.println(date);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));

it outputs: Mon Jun 03 00:00:00 EDT 2013 Current Date Time : 2013-06-24 12:52:04

I want to change the first date printed in first line to look like the second date printed in second line. how can I do this? thanks in advance.

tkyass
  • 2,968
  • 8
  • 38
  • 57

5 Answers5

5

You cannot influence what the Date#toString method does (unless you are willing to subclass Date, which would not be advised). Simply put, don't rely on Date#toString—that's what SimpleDateFormat is for.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • Or use JodaTime, where you can use something like `DateTime.now().toString("yyyy-MM-dd")` method for formatting. – Rohit Jain Jun 24 '13 at 17:07
2

Well, you can see the toString method of the Date object! you will see that the toString outputs the Date object like the format bellow:

EEE MMM dd HH:mm:ss zzz yyyy

That's why DateFormat comes into the party to format the Date object, to serve our demand of formatting it as our wish!

1

I think you're confusing yourself because you're creating a date using SimpleDateFormat#parse specifying a mask and it's not being "kept" after printing it, right?

The point is: no matter how you create a Date object, it will always use it's default mask when you print it - that is something like Mon Jun 03 00:00:00 EDT 2013.

If you want to change the way it's printed, you could use a SimpleDateFormat, just as you did in your post:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse("2013-06-03 00:00:00");
dateFormat.format(date);

Just to be clear about it: SimpleDateFormat does not change the date object in any way. It's purpose is only to format and parse date objects.

Marlon Bernardes
  • 13,265
  • 7
  • 37
  • 44
0

Use the same DateFormat to print the first Date object as well.

System.out.println(dateFormat.format(date));

How, println() prints out the Date object depends on how Date.toString() has been implemented. You cannot change the format unless you extend and override the Date class which obviously, isn't the right approach.

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = dateFormat.parse("2013-06-03 00:00:00");

    System.out.println(date); // formats as: EEE MMM dd HH:mm:ss zzz yyyy

    System.out.println(dateFormat.format(date));
    System.out.println("Current Date Time: " +
                       dateFormat.format(Calendar.getInstance().getTime()));
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
0

Well, combine the two, no?

System.out.println(dateFormat.format(date));
T-Bull
  • 2,136
  • 2
  • 15
  • 17