-2

I am trying to change the format of Date objects, I am trying to do it in this way:

for(Date date : dates){
    DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
    String formatterDate = formatter.format(date);
    Date d = formatter.parse(formatter.format(date));                      
}

But this does not have any effect on the d object, it is still with the old format, can't really understand why it is like that.

tano9321
  • 31
  • 7
  • 8
    A date [has no format](https://cdn.meme.am/Instance/Preview?imageID=15018536&text0=&text1=A%20date%20has%20no%20format). –  Jun 01 '17 at 11:41
  • https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/ – Oleg Estekhin Jun 01 '17 at 11:41
  • Related (though about `GregorianCalendar`): [How to initialize Gregorian calendar with date as YYYY-MM-DD format?](https://stackoverflow.com/questions/44180575/how-to-initialize-gregorian-calendar-with-date-as-yyyy-mm-dd-format/44182779#44182779) – Ole V.V. Jun 01 '17 at 12:12

4 Answers4

3

Please try to keep two concepts apart: your data and the presentation of the data to your user (or formatting for other purposes like inclusion in JSON). An int holding the value 7 can be presented as (formatted into) 7, 07, 007 or +7 while still just holding the same value without any formatting information — the formatting lies outside the int. Just the same, a Date holds a point in time, it can be presented as (formatted into) “June 1st 2017, 12:46:01.169”, “2017/06/01” or “1 Jun 2017” while still just holding the same value without any formatting information — the formatting lies outside the Date.

Depending on your requirements, one option is you store your date as a Date (or better, an instance of one of the modern date and time classes like LocalDate) and keep a formatter around so you can format it every time you need to show it to the user. If this won’t work and you need to store the date in a specific format, then store it as a String.

Java 8 (7, 6) date and time API

Now I have been ranting about using the newer Java date and time classes in the comments, so it might be unfair not to show you that they work. The question tries to format as yyyy-MM-dd, which we may do with the following piece of code.

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd");
    for (LocalDate date : localDates) {
        String formatterDate = date.format(dateFormatter);
        System.out.println(formatterDate);
    }

In one run I got

2017/05/23
2017/06/01

Should your objects in the list have other types than LocalDate, most other newer date and time types can be formatted in exactly the same way using the same DateTimeFormatter. Instant is a little special in this respect because it doesn’t contain a date, but you may do for example myInstant.atZone(ZoneId.of("Europe/Oslo")).format(dateFormatter) to obtain the date it was/will be in Oslo’s time zone at that instant.

The modern classes were introduced in Java 8 and are enhanced a bit in Java 9. They have been backported to Java 6 and 7 in the ThreeTen Backport with a special edition for Android, ThreeTenABP. So I really see no reason why you should not prefer to use them in your own code.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

Try this one.

String formattedDate = null;
    SimpleDateFormat sdf = new SimpleDateFormat(format you want);
    formattedDate = sdf.format( the date you want to format );
   return formattedDate;
Rakesh Bhagat
  • 397
  • 2
  • 5
  • 22
-1

some not best solution, but it works: this method will convert Date object to String of any pattern you need

public static void format(Date date){
   String pattern = "MMM d yyyy";
   LocalDateTime localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
   DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
   String result = formatter.format(localDate);
   // new Date() -> Jun 1 2017
 }
Vitaliy Moskalyuk
  • 2,463
  • 13
  • 15
  • 1
    I wanted to upvote because you are showing that one may do without the outdated classes `Date` and `SimpleDateFormat` and how to use the modern clases instead. Then I wanted to downvote because you are not really solving the OP’s problem: just like `Date` a `LocalDateTime` does not hold a format in it. So I did neither. – Ole V.V. Jun 01 '17 at 12:55
-1

SimpleDateFormat is useful while converting Date to String or vice-versa. java.util.Date format will always remain same. If you want to display it in standalone application then use date.getxxx() methods and choose your design.

  • 1
    The deprecated `getXx` methods (`getDate()`, `getYear()` etc.)?? While I recommend you stay away from the outdated `Date` class altogether, you should *most certainly* stay away from the methods that have been deprecated since around Java 1.1. – Ole V.V. Jun 01 '17 at 12:58
  • @Ole V.v ...Do you really think java.util.Date class is outdated ? Which java class you are using for date time ? – Biraj Sahoo Jun 01 '17 at 13:40
  • @BirajSahoo For java <= 7 you can use [ThreeTen Backport](http://www.threeten.org/threetenbp/) and for java >=8 there's the new [java.time API](https://docs.oracle.com/javase/tutorial/datetime/iso/overview.html). Those both libs are **much better** than `java.util.Date`, as they fix lots of its problems - more on that: [here](https://stackoverflow.com/q/1571265/7605325) and [here](http://www.jroller.com/cpurdy/entry/the_seven_habits_of_highly) –  Jun 01 '17 at 13:50
  • 2
    Yes, I seriously think so. See [What's wrong with Java Date & Time API?](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api) and [Why is the Java date API (java.util.Date, .Calendar) such a mess?](https://stackoverflow.com/questions/1571265/why-is-the-java-date-api-java-util-date-calendar-such-a-mess) – Ole V.V. Jun 01 '17 at 16:50
  • 1
    The short answer to which classes I use instead? The modern (2014) Java date and time classes are a handful each suited for a particular need, so it’s not going to be short. `LocalDate` for a date without time and without time zone. `Instant` for a point in time indedendent of time zone. And some more. See [the tutorial](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 01 '17 at 16:54
  • For the date in the question, where it seems time of day is not interesting, `LocalDate` would be the right choice. – Ole V.V. Jun 01 '17 at 16:56
  • I have added an example to [my answer](https://stackoverflow.com/a/44307180/5772882). – Ole V.V. Jun 01 '17 at 17:16