Convert Date to String in java

-1

I am consuming a web service where I consult an id parameter, and it returns a vehicle object that contains several attributes of type int and string , but the field date I returned it as date.

"this is in the database", what I need is to convert that attribute to string to be able to print it by a form.

I followed what you told me and I get an error.

The method is this:

public static void main(String[] args) {

    ServiciosVehiculosService AAA = new ServiciosVehiculosService();
    ServiciosVehiculos BBB = AAA.getServiciosVehiculosPort();
    ViewVEHICULOWEB XVARIABLEX = new ViewVEHICULOWEB();
    XVARIABLEX.setPLACA("QYA456");
    ViewVEHICULOWEB XXX = BBB.consultarViewVehiculoWeb(XVARIABLEX);

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println(sdf.format(XXX.getFECHAREG()));
}

And the error this:

  

Failed to execute goal org.codehaus.mojo: exec-maven-plugin: 1.2.1: exec   (default-cli) on project WebProject: Command execution failed.   Process exited with an error: 1 (Exit value: 1) - > [Help 1]

     

To see the full stack trace of the errors, re-run Maven with the -e   switch Re-run Maven using the -X switch to enable full debug logging.

    
asked by alejoecheverri444 28.03.2017 в 18:31
source

3 answers

3

Use SimpleDateFormat :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String fechaComoCadena = sdf.format(new Date());
System.out.println(fechaComoCadena);
    
answered by 28.03.2017 в 18:34
1

Hello as Luggi said, use SimpleDateFormat to show the dates in the format you want or to reconstruct it from a text string. His most basic example is:

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

// Esto muestra la fecha actual en pantalla, más o menos así 28/03/2017
System.out.println(sdf.format(new Date()));

Of course you can modify the mask of the date so that the output is in another format like YYYY-DD-MM, YY-MM-DD, etc.

For further reference, it is always advisable to read the official documentation and, of course, search a bit beforehand.

SimpleDateFormat

    
answered by 28.03.2017 в 18:40
1

When the client of a web service of type SOAP is generated and it contains data types xsd:date , these are mapped , by default, to type javax.xml.datatype.XMLGregorianCalendar of Java.

According to §2.3. Using different types of data (in English):

  

XMLGregorianCalendar is designed to be 100% compatible with the date / time system of the XML schema, such as providing infinite precision in sub-seconds and years, but often the ease of use of Java family classes wins over compatibility accurate.

So it is necessary to make a conversion to java.util.Date if you want to use an instance of java.text.SimpleDateFormat . That is:

java.util.Date date = XXX.getFECHAREG().toGregorianCalendar().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(sdf.format(date));
    
answered by 28.03.2017 в 20:32