简体   繁体   中英

Converting date and time strings to date in specific format

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

java.time

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM