Reputation: 5101
I am working on an Android app.
I get a date String and a time string from a JSON
file.
fecha_reporte = "2017-12-17"
hora_reporte = "23:51:00"
I need to convert both strings into a date variable, then later I will need to make some calculations with it.
This is what I have so far:
String fecha = fecha_reporte + " " + hora_reporte;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd H:m:s");
String dateInString = fecha;
try {
Date date2 = formatter.parse(dateInString);
System.out.println(date2);
System.out.println(formatter.format(date2));
Log.d("DURACION","DURACION REPORTE: calculado: "+date2);
} catch (ParseException e) {
e.printStackTrace();
}
The output is a date, but with this format:
Sun Dec 17 23:51:00 GMT-07:00 2017
I need it with following format: 2017-12-17 23:51:00
Upvotes: 0
Views: 88
Reputation: 340158
You are using troublesome old date time classes that are now legacy. Avoid them. Now supplanted by the java.time classes.
Parse your input strings as LocalDateTime
as they lack information about time zone or offset-from-UTC.
Add a T
to comply with standard ISO 8601 format.
String input = "2017-12-17" + "T" + "23:51:00" ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
Generate a String in your desired format by calling toString
and replace the T
in the middle with a SPACE.
ldt.toString().replace( "T" , " " ) ;
Alternatively, generate strings in custom formats using DateTimeFormatter
class.
For earlier Android, see the ThreeTen-Backport and ThreeTenABP projects.
Upvotes: 2