Date output format with DateFormat

5

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

Since I pass 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 format it correctly, 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

    
asked by jmgc1982 01.04.2016 в 09:46
source

1 answer

8

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

  • one to parse (convert String to Date )
  • another to format (convert Date to String in the 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));

DEPARTURE

31/03/16

ONLINE DEMO

ADDED

  

Anyway, I do not understand why DateFormat.getDateInstance().format(this.date) does not work 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, since this version the way in which Locale.getDefault() works is changed.

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

You can check the problem in this bug reported

SOURCE

    
answered by 01.04.2016 / 09:57
source