java – Date output format with DateFormat

Question:

I want to have the following date format when performing a System.out.println() : 31/03/2016 .

As they pass me the format in a String type in this way "31-03-2016" , I use the classes

import java.util.Date;

import java.text.DateFormat;

java.text.SimpleDateFormat;

to give it correct formatting, and I use this form:

SimpleDateFormat d = new SimpleDateFormat("dd-MM-yy");
Date date = d.parse("31-03-2016");
System.out.println(DateFormat.getDateInstance().format(date));

But it shows me: 31-03-2016

Answer:

Since the standard of your system is hyphenated, you need 2 SimpleDateFormat :

  • one to parse (convert String to Date )
  • another to format (convert Date to String in desired format)

Your code will be something like this:

// el que parsea
SimpleDateFormat parseador = new SimpleDateFormat("dd-MM-yy");
// el que formatea
SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yy");

Date date = parseador.parse("31-03-2016");
System.out.println(formateador.format(date));

EXIT

31/03/16

ONLINE DEMO


ADDED

Anyway, I don't understand why DateFormat.getDateInstance().format(this.date) and it shows me 31-mar-2016 since I use a Windows 7 64bits Spanish, and my date format is: dd/MM/aaaa

It happens because you use Java 7 or higher, as of this version the way Locale.getDefault() works has Locale.getDefault() .

To summarize, you have to modify not only the format of the region, but also change the way the language displays dates.

You can check the problem in this reported bug

SOURCE (IN)

Scroll to Top